2016-12-03 151 views
2

我想补充类body标签查看类别及其所有子类别,代码波纹管工作的时候,但它只是添加类的类别中的问题,但不是它的所有子类别:将主体类添加到类别及其所有子类别| Woocommerce

add_filter('body_class','custom_body_class'); 
function custom_body_class($classes) { 

    if (is_product_category(802)) { 
     $classes[] = 'class1'; 
    } else if (is_product_category(array('femme', 'homme', 'enfant'))) { 
     $classes[] = 'class2'; 
    } 

    return $classes; 

} 

我试图取代is_product_categoryin_category或is_product_tag但它也不管用。

任何帮助,将不胜感激。

+0

我不知道我正确理解你的问题。你想添加css类到类别页面和它的所有子类别页面吗?这就是说,我有一个名为水果类别和子类别的苹果,柠檬......你想与苹果和柠檬在它的身上都有CSS类名果子类别页面? – ucheng

+0

是LoicTheAztec红粉我很好的解决方案,还是要谢谢你ucheng! – colapsnux

回答

2

你需要,而不是使用相关的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; 

} 

这种方式查看类别或子类至极不含产品,不添加自己的身体自定义类时,你应该避免的情况下...

+1

它就像这样的魅力,谢谢你! – colapsnux

+0

当观看类别或子类别包含至极没有产品,不添加类,它是正常?无论如何,该类别是否有产品添加类的方法? – colapsnux

+0

@colapsnux has_term()仅适用于发布或自定义帖子作为产品...所以让我想一想...对于没有产品的类别,您可以在具有“OR”的条件下将has_term()与is_product_category()结合...但对于没有产品的子类别,我还不知道......我必须在提供工作解决方案之前进行一些测试。 – LoicTheAztec

相关问题