phpwordpresswoocommerceproductadvanced-custom-fields

Add a class to products in WooCommerce category archive pages based on ACF field


I'm trying to add a class for the product using add_filter + ACF value (True/false):

add_filter('post_class', function($classes, $class, $product_id) {
    if(is_product_category()) {
        if(get_field('product_new',$product_id)) {
            $classes = array_merge(['product_new_class'], $classes);
        }
    }
    return $classes;
}, 10, 3);

But it doesn't work. Why?


Solution

  • The following will add a class to each product in product category archive pages, depending on an ACF custom field value.

    First, you need to be sure that there is a "product_new" ACF field name set for "product" WooCommerce post type.

    Here is the revised code:

    add_filter( 'woocommerce_post_class', function( $classes, $product ) {
        if( is_product_category() && get_field( 'product_new', $product->get_id() )*/ ) {
            $classes[] = 'my-custom-class';
        }
        return $classes;
    }, 10, 2);
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.