I have a Woocommerce product and I need to display on that page the Most top level category of a category assigned to the product
- Main Product Category
-- Sub Product Category
--- Category Assigned to product
I need to get the ID or name of “Main Product Category” so that I can display it in the single product category.
I already tried doing the following:
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
$thetop_parent = woocommerce_get_term_top_most_parent( $product_cat_id , 'product_cat' );
echo $thetop_parent;
}
But It didn’t worked at all and it brakes the page from loading after woocomerce_get_term… I’m not sure what to do at this point It
thanks for any help on this.
or maybe this:
After a lot of research I figured a way to solve this. I hope this will help someone.
solution:
Here the solution i actually use
I know this is an old post, but I had a similar situation where we needed to get the root category of the current product being viewed. The simplest solution I could think of was to look at how WooCommerce does its breadcrumbs, and this piece of code is what did the trick for me:
For those looking for a clean solution, I’ve extended @Nicolas GRILLET’s function so that you only need to pass in a product ID and you get the term ID, Name and Link (URL).
This will give you an array of all the top-level categories a product belongs to.
Assuming your products only have one top-level category then the example below shows how to get the product’s top-level category id, name and link.
Here if u have the a “category_ID”
Use this to get the Top Parent Category: