Retrieve categories of a WooCommerce product in hierachical order

The get_category_parents is a function that retrieve the parent categories passing as argument a category id.

So, if you have a product and you want to retrieve a list of attached categories to it, the right function is get_the_terms.That function return all the categories objects, without order, and so you can take the first of these categories and call get_category_parents.

Assuming the $product variable contain a post object, you can use

$cats = get_the_terms( $product->ID, 'product_cat' );
echo $cats ? get_category_parents( array_shift($cats)->term_id ) : '';

Leave a Comment