如果您希望此功能适用于woocommerce类别,可以首先将逻辑限制为仅适用于woocommerce类别is_product_category
, 这将有助于防止代码在不需要时运行。
使用WordPressget_ansestors
您可以获得当前类别的顶级等级类别(分类法),无论它有多深。
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\');