WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I found this code, which apparently gets the category ID from the category slug:

  $category = get_category_by_slug('category-name'); 
  $id = $category->term_id;

But when I try to implement it into the following code, it doesn't work:

//list terms in a custom taxonomy using wp_list_categories 

$category = get_category_by_slug( 'military' );

$args = array(
  'taxonomy'     => 'product_cat',
  'orderby'      => 'name',
  'show_count'   => 0,
  'pad_counts'   => 0,
  'hierarchical' => 1,
  'title_li'     => '',
  'depth'        => 2,
  'child_of'     => $category->term_id


<ul class="test">
<?php wp_list_categories( $args ); ?>

I'm attempting to show only the child categories of a specific parent category. If I just type the category ID for "child_of" then it works perfectly. But using the above code, it continues to show all categories. Unfortunately I need to do it via slug, not via ID.

Any ideas?

share|improve this question
up vote 5 down vote accepted

You can't use get_category_by_slug() with a custom taxonomy. You need to use get_term_by().

$category = get_term_by( 'slug', 'military', 'product_cat' );
share|improve this answer
Ah, I didn't realize that. Thank you! However, I tried replacing the line $category = get_category_by_slug... to match what you wrote above, and it still did not work. Do I need to change the "child_of" line as well? – LBF Apr 11 '13 at 20:24
Can you dump the $category object to make sure it exists. var_dump( $category ); After the call to get_category_by_slug(). – Chris_O Apr 11 '13 at 20:28
I did the dump, and it gave me this: object(stdClass)#771 (10) { ["term_id"]=> string(3) "144" ["name"]=> string(31) "Military Bands" ["slug"]=> string(11) "military" ["term_group"]=> string(1) "0" ["avhec_term_order"]=> string(1) "0" ["term_taxonomy_id"]=> string(3) "144" ["taxonomy"]=> string(11) "product_cat" ["description"]=> string(238) "Watch Straps" ["parent"]=> string(1) "0" ["count"]=> string(3) "163" } – LBF Apr 11 '13 at 22:19
Ah! I had spelled category wrong in my code when I typed in your new line. Argh. It's always the stupid mistakes. Thank you -- this worked! – LBF Apr 11 '13 at 22:30
See for example without shouting capitals: get_category_by_slug how to get the ID. – Charles Jun 2 at 14:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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