【问题标题】:Add the product attribute term name to body class in WooCommerce在 WooCommerce 中将产品属性术语名称添加到正文类
【发布时间】:2018-02-24 22:07:32
【问题描述】:

我希望根据产品的属性添加一个 body 类,例如颜色,所以如果产品颜色是红色,我希望将类“red”添加到 body 标签。

我会用什么钩子来做到这一点?

【问题讨论】:

    标签: php wordpress woocommerce product hook-woocommerce


    【解决方案1】:

    这可以通过挂在 body_class 过滤器挂钩中的自定义函数来完成:

    add_filter( 'body_class', function( $classes ) {
        if( ! is_product() ) return $classes;
    
        global $post;
        $custom_classes = array();
    
        $product = wc_get_product( $post->ID );
    
        foreach( $product->get_attributes() as $taxonomy => $wc_attribute ){
            if( $taxonomy == 'pa_color' )
                $custom_classes = $wc_attribute->get_slugs();
    
        return array_merge( $classes, $custom_classes );
    } );
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    此代码在 Woocommerce 3+ 上经过测试并且可以正常工作。

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2019-12-24
      • 2021-01-05
      • 2019-05-11
      • 2022-01-23
      • 2018-11-04
      • 2018-05-04
      • 1970-01-01
      • 2017-03-27
      相关资源
      最近更新 更多