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
1

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' );

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *