get_terms parent for current product only

I wish someone can give me a clue.

I am actually displaying all product category (product_cat taxonomy) on single page products, displaying also childs regarding the product itself.

For instance: Product-A has Cat1-parent > Cat1-child1, Cat1-child2 => The code display them properly but also will display any other Parent Category that belongs to an another existing product…. result I get an extra parent category displaying with no childs.

So Id like to display only parent categories that belongs to the product itself.

I think I am missing some knowledge in the beginning of the code with the get_terms function

$parents = get_terms( 'product_cat' , array( 'parent' => 0 ) );

foreach( $parents as $parent ):

echo '<div class="parent '.$parent->slug.'">' . $parent->name . '</div>';

2 Answers
2

get_terms relates to getting all the terms of a taxonomy. get_the_terms grabs all the terms related to the post.

The problem is that it sounds like you only want to return those terms which are parent categories, not the children, and get_the_terms does not pass an arguments array.

$terms = get_the_terms( get_the_ID(), 'product_cat' );

foreach ( $terms as $term ){
    if ( $term->parent == 0 ) {
        echo '<div class="parent '.$term->slug.'">' . $term->name . '</div>';
    }
}

Leave a Comment