0

I'm trying to get_term_children of a specific term:

$style_categories = get_term_children( 29, 'product_cat' ); 

if ( $style_categories ) :

    foreach ( $style_categories as $style ) :

        $child = get_term_by( 'id', $style, 'product_cat' );

        echo '<h3>' . $child->name . '</h3>';

              // post query goes here

    endforeach;

endif;

This works, but it shows terms when they're empty, and there doesn't appear to be a hide_empty option for get_term_children.

Is there a way to do this?

1 Answer 1

1

With the get_term_children() function there is nothing to pass which will hide empty terms. You could do that in your foreach as each term has a property which holds how many posts it is assigned:

foreach( $style_categories as $style ) {
    
    $child = get_term_by( 'id', $style, 'product_cat' );
    
    // Skip empty terms
    if( $child->count <= 0 ) {
        continue;
    }
}

The way it stands now you're creating multiple queries - a better solution would be to use get_terms() instead.

get_terms( [ 'taxonomy' => 'product_cat', 'child_of' => 29] );

get_terms will hide the terms that have no post, you can change that with the hide_empty argument.

5
  • @LBF - Can this type of functionality not be achieved with get_terms()? I've updated my answer but it's probably inefficient.
    – Howdy_McGee
    Jun 10, 2016 at 18:46
  • 1
    Oh right -- I guess I could just use child_of with get_terms to do the same thing? D'oh.
    – LBF
    Jun 10, 2016 at 20:27
  • @LBF - if that works for you post it as an answer - I'm not sure the core differences between the two functions but as it stands now you're making a ton of extra queries.
    – Howdy_McGee
    Jun 10, 2016 at 20:28
  • 1
    It did work, thank you. But you're right. I'll use get_terms instead. Not sure how I got so twisted around. Still learning...
    – LBF
    Jun 10, 2016 at 20:30
  • I've added the get_terms() example in the edited solution.
    – Tim
    Aug 26, 2020 at 7:37

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.