10

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:

<?php
//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 ); ?>
</ul>

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?

1 Answer 1

20

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' );
5
  • 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, 2013 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, 2013 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, 2013 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, 2013 at 22:30
  • See for example without shouting capitals: get_category_by_slug how to get the ID.
    – Charles
    Jun 2, 2016 at 14:50

Your Answer

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

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