如何删除添加到 Woocommerce li.product 的 类?

How to remove classes added to Woocommerce li.product?

Woocommerce 将指定的产品类别和属性作为自定义 类 添加到 li.product

<li class="post-120 product type-product status-publish has-post-thumbnail 
category1 category2 category3 category4 pa_one pa_two...">

我们为每个产品分配了很多类别,这会降低网站速度。有没有办法删除那些额外的 类?

如果您知道 php,您可以编辑 woocoommerce php 模板文件以删除那些额外的 类。 如果你打开文件,有一个 php 变量要额外添加 类,它是一个数组。

我建议对 post_class 函数应用一个过滤器,而不是编辑模板,因为 woocommerce 会定期更新这些模板,并且很难掌握它们。为此,您可以检查您是否在产品循环中,或者是否存在要从产品页面中删除的产品,如下所示:

add_filter( 'post_class', function($classes){
$product = wc_get_product();
return ($product) ? array('product'  'or-any-class-you-want') : $classes; } , 9999 );

在 woocommerce 插件“3.6.2”中,文件 'wc-template-functions.php' 它说:

// 注意,要更改 类,您需要使用较新的 woocommerce_post_class 过滤器。

所以要删除 'first' & 'last' 类 我使用了:

add_filter( 'woocommerce_post_class', 'remove_post_class', 21, 3 ); //woocommerce use priority 20, so if you want to do something after they finish be more lazy
function remove_post_class( $classes ) {
    if ( 'product' == get_post_type() ) {
        $classes = array_diff( $classes, array( 'last','first' ) );
    }
    return $classes;
}

我使用的产品类别:

add_filter( 'product_cat_class', 'remove_category_class', 21, 3 ); //woocommerce use priority 20, so if you want to do something after they finish be more lazy
function remove_category_class( $classes ) {
    if ( 'product' == get_post_type() ) {
        $classes = array_diff( $classes, array( 'last','first' ) );
    }
    return $classes;
}