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())?

  • though, i haven't tried, the get_the_category_list function has an optional paremeter on how to display the parents -> codex.wordpress.org/Function_Reference/get_the_category_list – gdaniel Apr 25 '16 at 18:20
  • @gdaniel Yep, but it doesn't appear to do the above as far as I can tell. It takes two options: 'single' or 'multiple'. – Django Reinhardt Apr 25 '16 at 21:46
  • Please elaborate on the "subcategories for a particular post" part? Do you mean post category siblings? – Z. Zlatev Apr 27 '16 at 17:06

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,
  • 7
    This assumes the user has selected the parent(s) category as well? I guess we could wrap this into: wp_list_categories( [ 'include' => wp_list_pluck( get_the_category(), 'term_id' ) ] ); for the compact version ;-) – birgire Apr 27 '16 at 17:41
  • @birgire :]] haven't known that WordPress has that badass function. Let me update the answer :) – sarahcoding Apr 27 '16 at 17:49
  • 2
    ps: just a note that if the include array is empty then wp_list_categories will show all the tree. But afaik there's always the fallback category (usually "uncategorized") so under normal circumstances it's not empty. But it's easy to fix that if necessary. – birgire Apr 27 '16 at 18:01
  • Why isn't include mentioned as an argument in the documentation? (developer.wordpress.org/reference/functions/wp_list_categories) Arg. – Django Reinhardt Apr 28 '16 at 9:23
  • 2
    There are missing arguments in the function's docblock, like style, pad_counts, class and walker? and then there are all the arguments supported by get_categories() or get_terms(), like include etc. I filed the ticket #36693 yesterday @DjangoReinhardt – birgire Apr 28 '16 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.