【问题标题】:Add extra class with product category IDs on WooCommerce archives pages在 WooCommerce 档案页面上添加带有产品类别 ID 的额外类
【发布时间】:2021-10-11 06:55:43
【问题描述】:

我想在产品存档页面的类别中添加一个自定义类,以便我可以将自定义样式添加到类别标签中。

例子:

  • 类别 1 中的产品 X --> 黄色类别标签

  • 类别 2 中的产品 Y --> 红色类别标签

我正在使用这个 php sn-p,但这是针对单个产品页面并应用于 <body> 元素。如何将其更改为也适用于商店存档页面?

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

    if ( is_product() ) {

        global $post;
        $terms = get_the_terms( $post->ID, 'product_cat' );

        foreach ($terms as $term) {
            $product_cat_id = $term->term_id;
            $classes[] = 'product-in-cat-' . $product_cat_id;    
        }
    }
    return $classes;
}

【问题讨论】:

    标签: wordpress woocommerce product


    【解决方案1】:

    您可以使用较新的woocommerce_post_class 过滤器挂钩

    所以你得到:

    /**
     * WooCommerce Post Class filter.
     *
     * @since 3.6.2
     * @param array      $classes Array of CSS classes.
     * @param WC_Product $product Product object.
     */
    function filter_woocommerce_post_class( $classes, $product ) {  
        // Returns true when viewing a product category archive.
        // Returns true when on the product archive page (shop).
        if ( is_product_category() || is_shop() ) {
            // Set taxonmy
            $taxonomy = 'product_cat';
            
            // Get the terms
            $terms = get_the_terms( $product->get_id(), $taxonomy );
            
            // Error or empty
            if ( is_wp_error( $terms ) || empty( $terms ) ) {
                return $classes;
            }
            
            // Loop trough
            foreach ( $terms as $index => $term ) {
                // Product term Id
                $term_id = $term->term_id;
                
                // Add new class
                $classes[] = 'product-in-cat-' . $term_id;
            }
        }
        
        return $classes;
    }
    add_filter( 'woocommerce_post_class', 'filter_woocommerce_post_class', 10, 2 );
    

    注意: if 条件可以用其他conditional tags 进行扩展/约束

    例子:

    • is_product() - 在单个产品页面上返回 true。 is_singular 的包装器。
    • 等等..

    要不应用这个,请在​​ if 条件中使用 !

    // NOT
    if ( ! is_product_category() )..
    

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      相关资源
      最近更新 更多