从 WooCommerce 产品循环中删除 "first" 和 "last" CSS 类

Remove "first" and "last" CSS classes from WooCommerce product loop

我正在使用过滤器从产品网格中删除“第一个”和“最后一个”类。

当我将 $classes 设置为 NULL 时,它会删除所有这些,但我的代码应该只删除这两个。但那是行不通的。

add_filter( 'post_class', 'prefix_post_class', 21 );
function prefix_post_class( $classes ) {
    if ( 'product' == get_post_type() ) {
        $classes = array_diff( $classes, array( 'first', 'last' ) );
        // $classes = NULL; <-- This works strangely enough
    }
    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 ) {
    // array_values() returns all the values from the array and indexes the array numerically.
    // array_diff - Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.
    $classes = array_values( array_diff( $classes, array( 'first', 'last' ) ) );
    
    return $classes;
}
add_filter( 'woocommerce_post_class', 'filter_woocommerce_post_class', 10, 2 );