0

The title sounds complex but this is quite simple. Hopefully the code for it is too. I have this custom taxonomy we'll call "Filters".

  • ParentTerm A
    • ChildTerm 1A
    • ChildTerm 2A
  • Parent Term B
    • Child Term 1B
    • Child Term 2B

On a page that has a listing of custom post types, I was easily able to display all the terms selected for the "Filters" taxonomy by putting this in my loop/query:

<?php
$terms = get_the_terms( $post->ID, 'filters' );                 
if ( $terms && ! is_wp_error( $terms ) ) : 
    $listing_filters = array();
    foreach ( $terms as $term ) {
        $listing_filters[] = $term->name;
    }                   
    $listing_filters = join( ", ", $listing_filters );
?>
<p class="listing-filters"><?php echo $listing_filters; ?></p>
<?php endif; ?>

The PROBLEM is for this page I only want to display the terms selected under ParentTerm A.

So ChildTerm 1A and ChildTerm 2A would display if they were checked off. But no other terms would display, not ParentTerm A, nor of course any terms in Parent Term B.

However as noted with the above code I of course get any and all selected terms for this custom taxonomy. Any ideas? Thanks!!

1

Each term has a term_id, and each has a parent. Child terms of ParentTerm A will have a parent value equal to ParentTerm A's term_id, so given the parent term's ID, you can test each term to see if the parent field matches-

$parent_term_id = 42;    
foreach ( $terms as $term ) {
    if( $term->parent == $parent_term_id )
        $listing_filters[] = $term->name;
}
  • Wow, that was too easy...I was definitely looking at solutions that were far more complex. Thank you! – Trevor Oct 11 '13 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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