将body类添加到其所有子类别的类别中Woocommerce

时间:2016-12-03 15:07:18

标签: php wordpress woocommerce categories product

我想在查看类别及其所有子类别时向body标签添加类,但代码如下工作但它只是将类添加到相关类别但不是所有子类别中:

UPDATE myTable SET col1 = newVal1 WHERE x = y
UPDATE myTable SET col3 = newVal3 WHERE x = y
...

我尝试将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_category或is_product_tag,但它也不起作用。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分: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(根据您的评论):

当归档类别(或子类别)页面为空时,可以使用 get_queried_object() 函数来获取当前术语对象,并调整函数中的条件来处理这些情况。 / p>

以下是代码:

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;

}

这样你就可以避免在查看不包含任何不添加你的身体自定义类的产品的类别或子类别时的情况......