this code works on the single-product.php (single product page). I had build the code following your diagram
- Island (parent)
- province (child)
- City (sub-child)
- province (child)
this means supposing the cities are a 3rd level category.
global $post; $cats = get_the_terms( $post->ID, 'product_cat' ); $count = 0; foreach ($cats as $parent){ if($parent->parent == 0){ foreach($cats as $child){ if($child->parent == $parent->term_id){ foreach($cats as $subChild){ if($subChild->parent == $child->term_id){ if($count){echo ', ';} echo $subChild->name; $count += 1; } } } } } } the global $post; is just to make sure it works, but try with out it, probably will work as well once where your code is working probably already have it.
if you are sure the city is always one doesnt need the coma between, so it can be use without that if statment.
$cats = get_the_terms( $post->ID, 'product_cat' ); foreach ($cats as $parent){ if($parent->parent == 0){ foreach($cats as $child){ if($child->parent == $parent->term_id){ foreach($cats as $subChild){ if($subChild->parent == $child->term_id){ echo $subChild->name; } } } } } }