For those who have problems with this method, I found a simple solution, perhaps not the best in terms of efficiency. To get the parent top level category on the post / product page
Using:
global $post; $terms = wc_get_product_terms( $post->ID, 'product_cat', array( 'orderby' => 'parent', 'order' => 'DESC' ) ); if ( ! empty( $terms ) ) { $main_term = $terms[0]; $root_cat_id = get_top_category($main_term->term_id);
Functions:
function get_top_category ($catid) { $cat_parent_id=0; while ($catid!=null & $catid!=0) { $current_term = get_term($catid); $catid = $current_term->parent; if($catid!=null & $catid!=0){ $cat_parent_id = $catid; }else{ $cat_parent_id = $current_term->term_id; } } return $cat_parent_id; }
source share