将Woocommerce父类别添加到WP'body'类

时间:2014-10-02 18:46:11

标签: php wordpress woocommerce

我正在尝试将Woocommerce中的产品父类别添加为wordpress' body标记。

每次进入子类别时,父类别不再在body类中。

是否可以编辑以下内容以查找父类别并在body标签中添加?

也许像" product_parent_cat"?这样的术语试过这个并搜索他们的API但没有成功..

function woo_custom_taxonomy_in_body_class( $classes ){
    $custom_terms = get_the_terms(0, 'product_cat');
    if ($custom_terms) {
      foreach ($custom_terms as $custom_term) {
        $classes[] = 'product_cat_' . $custom_term->slug;
      }
    }
  return $classes;
}

add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' );

1 个答案:

答案 0 :(得分:8)

您可以尝试此修改(未经测试):

function woo_custom_taxonomy_in_body_class( $classes ){
    $custom_terms = get_the_terms(0, 'product_cat');
    if ($custom_terms) {
      foreach ($custom_terms as $custom_term) {

        // Check if the parent category exists:
        if( $custom_term->parent > 0 ) {
            // Get the parent product category:
            $parent = get_term( $custom_term->parent, 'product_cat' );
            // Append the parent class:
            if ( ! is_wp_error( $parent ) )
                $classes[] = 'product_parent_cat_' . $parent->slug;   
        }

        $classes[] = 'product_cat_' . $custom_term->slug;
      }
    }
    return $classes;
}

add_filter( 'body_class', 'woo_custom_taxonomy_in_body_class' );

将父产品类别slugs添加到body类。

这里我们使用parent函数返回的术语对象的get_term()属性。

相关问题