1

I have created WC product categories and subcategories like: Gear (main category) -> Masks (subcategory) -> Full face masks (subcategory's subcategory) ... so on...

When I use $variations = get_the_terms( the_ID() , 'product_cat' ); on single-{custom-post-type}.php page, I am getting all categories and subcategories. But I want to show only

Full face masks (subcategory's subcategory)

How can I do that any idea or solution?

1

Using wp_list_pluck to return an array in the form of array(term_id => parent, ...), you can do the following (explanation is given in the comments):

$variations = get_the_terms( the_ID() , 'product_cat' );
if(is_array($variations)) { //make sure terms were returned
    $parents = wp_list_pluck( $variations, 'parent', 'term_id' );
    foreach ($variations as $variation) {
        if($variation->parent && $parents[$variation->parent] && !$parents[$parents[$variation->parent]]) { //if parent's parent has no parent (parent==0) i.e. a top level term (0 evaluates to false when treated as a boolean)
            //display term
        }
    }
}

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.