首页 > 解决方案 > 在 WooCommerce 档案页面上添加带有产品类别 ID 的额外类

问题描述

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

例子:

我正在使用这个 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;
}

标签: wordpresswoocommerceproduct

解决方案


您可以使用较新的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 条件可以用其他条件标签扩展/约束

例子:

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

要不应用此功能,!请在 if 条件中使用:

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

推荐阅读