4

I want to list categories belonging to a parent. The problem is using category id's isn't useful and makes things harder to understand.

Is there any easier way to list categories belonging to a parent, similar to the default way supplied in the WP codec?

<?php wp_list_categories('child_of=8'); ?> //what category is '8' ?!

<?php wp_list_categories('child_of=clients'); ?> //much nicer, but doesn't work

I would prefer to avoid using another query in the loop, but to make sense to other developers, I might have to.

2 Answers 2

5

You can get ID from slug quite easily:

$category = get_category_by_slug( 'clients' );
wp_list_categories('child_of='.$category->term_id);
1
  • 1
    I nearly suggested similar using get_term_by.. get_cat_ID is just easier to use because there's no need to reference object properties. +1 from me though, still a valuable answer!.. :)
    – t31os
    Feb 1, 2011 at 12:19
3

Do you want all children on a set category then, as that's essentially what the child_of parameter is for, getting all descendants of a term(category).

If you want only terms that have a particular direct parent then you should instead be using parent.

In regard to using an ID, this should work..

<?php
// Get ID for the named category
$cat_term_id = get_cat_ID( 'my-cat' );

wp_list_categories("parent=$cat_term_id");
//wp_list_categories("child_of=$cat_term_id");
?>

get_cat_ID docs.


Hope that helps..

4
  • NOTE: get_cat_ID also expects the slug, and not the name, like with get_category_by_slug .. (however this will give you just the ID, and not an object).
    – t31os
    Feb 1, 2011 at 12:16
  • ehm, I thing your note is backwards :) get_cat_ID() expects name, get_category_by_slug() expects slug.
    – Rarst
    Feb 1, 2011 at 12:20
  • @Rarst - Apologies, my mistake, it does indeed expect the name(i just had this memory in my head about a category function that is documented to expect a name, but actually expects the slug - i got my wires crossed).. ;)
    – t31os
    Feb 1, 2011 at 12:36
  • I too remember some function being like that, but it is neither of these two... yay for having too many functions :)
    – Rarst
    Feb 1, 2011 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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