In WordPress WooCommerce Looking to find out Product Top level Category ID ? with use of below script code you able to find out Top level category id for any Product in Woocommerce.
With help of Following code its easy to get Top Level Category ID for any Product.
function wdo_get_product_top_level_category ( $product_id ) { $product_top_category=''; $prod_terms = get_the_terms( $product_id, 'product_cat' ); foreach ($prod_terms as $prod_term) { $product_cat_id = $prod_term->term_id; $product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' ); $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true); foreach($last_parent_cat as $last_parent_cat_value){ $product_top_category = $last_parent_cat_value; } } return $product_top_category; } // Call above function to get top level category for Product ID $parent_cat_id = wdo_get_product_top_level_category($post->ID);
Get Top Level Category for Child Category
With few modification in above code you able to Get Top Level Category ID for any nth level child category in WordPress
# global $wp_query; $cat = $wp_query->get_queried_object(); $product_cat_id = $cat->term_taxonomy_id; $product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' ); if(count($product_parent_categories_all_hierachy)>0) { $last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true); foreach($last_parent_cat as $last_parent_cat_value){ $product_cat_id = $last_parent_cat_value; } } return $product_cat_id;