Listing a post's categories and subcategories

Is there a way to display the parent categories and subcategories for a particular post (ie. for use on single.php).

I’ve tried using get_the_category_list(), but it displays a list like this:

  • Subcat1
  • ParentCat1
  • Subcat2
  • Subcat3
  • ParentCat2

Even if you try the ‘single’ or ‘multiple’ display argument, it doesn’t give me what I want, which is this:

  • ParentCat1
    • Subcat1
    • Subcat2
  • ParentCat2
    • Subcat 3

Is it possible to get the categories to be displayed like this? Even using another method (like get_terms())?

Solutions Collecting From Web of "Listing a post's categories and subcategories"

Update 1:

Thanks to @birgire for suggesting a better way:

wp_list_categories( [ 'include' => wp_list_pluck( get_the_category(), 'term_id' ) ] );

Try this in your single.php template:

$current_cats = get_the_category();
$current_cats_ids = [];

foreach ($current_cats as $cat) {
    $current_cats_ids[] = $cat->term_id;

    'include' => $current_cats_ids,