I’m using this code and getting only a forward slash for results. I’m trying to print the parent category of a WooCommerce product.
$prod_cat = get_category_parents($product->id);
echo $prod_cat;
Any idea how to modify it so it prints the parent categories name?
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 callget_category_parents
.Assuming the
$product
variable contain a post object, you can useBelow code should do what you want, it has the benefit of working in
product
andproduct category
environments. Besides that it has some options build in, as described underhow to use
.code
how to use
wc_origin_trail_ancestor();
wc_origin_trail_ancestor(true);
wc_origin_trail_ancestor(false,true);
wc_origin_trail_ancestor(true,true);
notes