在 WooCommerce 存档页面上添加带有产品类别 ID 的额外 class

Add extra class with product category IDs on WooCommerce archives pages

我想向产品存档页面上的类别添加自定义 class,以便我可以向类别标签添加自定义样式。

示例:

我正在使用此 php 代码段,但它适用于单个产品页面并应用于 <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;
}

您可以使用较新的 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条件可以extended/constrained与其他conditional tags

示例:

  • is_product() - Returns 在单个产品页面上为真。 is_singular.
  • 的包装器
  • 等..

To NOT apply this, use ! in the if condition:

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