Can someone please help me, I’m looking for a way to find the main parent product category of a WooCommerce product? Say, the product is marked under Gadgets, but the main parent of them all is Electronics.
I want this per post, as I want to add a class to each post signifying its main parent product_cat
.
Please remember, product categories are custom taxonomy, and cannot be retrieved using get_category_parents()
. They are listed as terms.
Thanks in advance.
// edit:
This is the code I have already, I’m calling this on each post and my posts are rendered similar to an archive page.
function all_cat_classes($post) {
$cats = "";
$terms = get_the_terms($post->ID, "product_cat");
$count = 0;
$count = count($terms);
$key = 0;
foreach ($terms as $cat) {
$key++;
}
return $cats;
}
just to offer a alternative solution that might help somebody:
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
I wrote my own function to go all the way up the “chain”. My recursive might not be the best implementation you’ve seen, but it works.
You can try this: