2

I have a site set up with the following:

  • Post Type: product
  • Taxonomy: product_cat
  • Taxonomy Slug: hydro

The term hydro has several immediate child terms and several grandchild terms.

I need to write a loop that will display only the first-level children of the custom taxonomy term "hydro" (i.e - skip grandchild terms), along with a permalink to their respective taxonomy archive pages.

I've tried working with get_terms() in various incarnations but I just can't get it right.

Any help is greatly appreciated. Thanks!

1 Answer 1

4

First of all you need the term id of hydro term, you can retrive it using get_term_by

$hydro = get_term_by('slug', 'hydro', 'product_cat');

After that, you can use the term id as 'parent' argument for get_terms

$hydro_children = get_terms( 'product_cat', array( 'parent' => $hydro->term_id ) );

Now you can display a list of this children:

if ( ! empty($hydro_children) ) {
  echo '<ul>';
  foreach( $hydro_children as $hydro_child ) {
    echo '<li><a href="' . get_term_link($hydro_child, 'product_cat') . '">';
    echo $hydro_child->name . '</a></li>';
  }
  echo '</ul>';
}

And/or run a post query for posts with $hydro_children terms attached, and if you want you can skip posts having only children of $hydro_children terms (grand children of 'hydro') thanks to 'include_children' argument of tax query:

$args = array(
  'post_type' => 'product', // I guess
  'tax_query' => array(
    array(
      'taxonomy' => 'product_cat',
      'field' => 'id',
      'terms' => wp_list_pluck($hydro_children, 'term_id'),
      'include_children' => false
    )
   )
);
$query = new WP_Query( $args );
3
  • Thanks for the help! I follow your logic and it looks good. However the foreach loop seems to be breaking my page. When I comment it out it displays properly, but of course it also hides the actual list that I need to display.
    – Evster
    Nov 8, 2013 at 20:41
  • @Evster Sure, I forgot first argument for get_terms. Now I've fixed it.
    – gmazzap
    Nov 8, 2013 at 20:51
  • Yep that was the problem! Should have caught it on my own, but apparently I've been staring at this code for too long.
    – Evster
    Nov 8, 2013 at 21:12

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.