1

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

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>';
    }
}
  • What to do if I only want to return just child terms, No parent only child. Please give me an idea. – Nimesh Jul 20 at 4:04
0

Thank you for the lesson. I understand better now. I just changed to my term name and inserted in my full function: $parents = get_the_terms( get_the_ID(), 'product_cat' );

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

You helped me a lot. Thank you!

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.