你需要,而不是使用相關的WordPress條件函數has_term()
與'product_cat'
分類參數爲目標的產品類別是這樣的:
add_filter('body_class','custom_body_class');
function custom_body_class($classes) {
if (has_term(802, 'product_cat')) { // assuming that 802 is the id of a product category.
$classes[] = 'class1';
} else if (has_term(array('femme', 'homme', 'enfant'), 'product_cat')) {
$classes[] = 'class2';
}
return $classes;
}
更新2(根據您的評論)
:
當歸檔類別(或子類別)PAG ES是空的,可以使用get_queried_object()
函數來獲得當期對象,並在你的函數修改條件來處理這些情況。
這裏是代碼:
add_filter('body_class','custom_body_class');
function custom_body_class($classes) {
// Only on product category (or subcategory) archives pages
if(is_product_category()):
// Set HERE your Main category ID (the parent ID of subcategories IDs)
$main_cat = 802;
// Set HERE your subcategories slugs
$sub_cats_arr = array('femme', 'homme', 'enfant');
// Getting the current term (object) of category or subcategory archives page
$term = get_queried_object();
// All the needed data from current term (object)
$term_id = $term->term_id; // term ID
$term_slug = $term->slug; // term slug
$term_name = $term->name; // term name
$term_taxonomy = $term->taxonomy; // Always 'product_cat' for woocommerce product categories
$term_parent_id = $term->parent; // the parent term_id
// FOR YOUR MAIN CATEGORY ID '802' (Handle empty archive page case too)
if (has_term($main_cat, $term_taxonomy) || $term_id == $main_cat)
$classes[] = 'class1';
// FOR YOUR MAIN 3 SUBCATEGORIES SLUGS (Handle empty archive page case too)
if (has_term($sub_cats_arr, $term_taxonomy) || in_array($term_slug, $sub_cats_arr))
$classes[] = 'class2';
endif;
return $classes;
}
這種方式查看類別或子類至極不含產品,不添加自己的身體自定義類時,你應該避免的情況下...
我不知道我正確理解你的問題。你想添加css類到類別頁面和它的所有子類別頁面嗎?這就是說,我有一個名爲水果類別和子類別的蘋果,檸檬......你想與蘋果和檸檬在它的身上都有CSS類名果子類別頁面? – ucheng
是LoicTheAztec紅粉我很好的解決方案,還是要謝謝你ucheng! – colapsnux