douyangcheng4965 2014-10-02 18:46
浏览 37
已采纳

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

I am trying to add a product's parent category from Woocommerce as a class to wordpress' body tag.

Every time I go within a child category the parent category is no longer within the body class.

Could something like below be edited to find the parent category and add within the body tag?

Maybe a term like "product_parent_cat"? Tried this and searched their API but no success..

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条回答 默认 最新

  • douya1248 2014-10-06 20:22
    关注

    You can try this modification (untested):

    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' );
    

    to add the parent product category slugs to the body class.

    Here we use the parent property of the term object returned by the get_term() function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 Python如何后台操作Vmwake虚拟机键鼠
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容