If you want this to work for woocommerce categories you can start by limiting the logic to only woocommerce categories with is_product_category
, that will help with preventing the code running when you don’t need it to.
Using WordPress get_ansestors
you can get the top lvl category (taxonomy) of the current category no matter how deep it is.
function woo_custom_taxonomy_in_body_class ($classes) {
if (is_product_category()) {
// get the current category (product_cat taxonomy)
$cat = get_queried_object();
if ($cat->parent == 0) { // if parent add it to body classes
$classes[] = 'product_cat_' . urldecode($cat->slug);
} else { // if not parent, find the top leven parent and add it
// get the category parents
$get_ancestors = get_ancestors($cat->term_id, 'product_cat');
// get top level parent id, because ancestors from lowest to highest
// we use PHPs end to get the last element of the array
$top_parent_cat_id = end($get_ancestors);
// using the parent id get the parent object
$top_parent_cat = get_term_by('id', $top_parent_cat_id, 'product_cat');
// get slug using the parent object
$classes[] = 'product_parent_cat_' . urldecode($top_parent_cat->slug);
}
} else if (is_product()) {
global $product;
// get the product categories and check if not empty
if (!empty($product_categories = get_the_terms($product->get_id(), 'product_cat'))) {
// this is a bit more complicated
// because product can have multiple categories we cannot always get the correct one
// for this example ill take the firdt category I find and work with it
// if you only have one category per product then this will work fine
// get the first category (product_cat taxonomy) that we find
$cat = $product_categories[0];
if ($cat->parent == 0) { // if parent add it to body classes
$classes[] = 'product_cat_' . urldecode($cat->slug);
} else { // if not parent, find the top leven parent and add it
// get the category parents
$get_ancestors = get_ancestors($cat->term_id, 'product_cat');
// get top level parent id, because ancestors from lowest to highest
// we use PHPs end to get the last element of the array
$top_parent_cat_id = end($get_ancestors);
// using the parent id get the parent object
$top_parent_cat = get_term_by('id', $top_parent_cat_id, 'product_cat');
// get slug using the parent object
$classes[] = 'product_parent_cat_' . urldecode($top_parent_cat->slug);
}
}
}
return $classes;
}
add_filter('body_class', 'woo_custom_taxonomy_in_body_class');