Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add a CSS class to WooCommerce cart items based on product category

I am trying to add the WooCommerce product class to the cart items on the cart page.

I have products in a specific category with faster shipping (quickship) and want to highlight them on the cart page to make my customers aware of it before check out.

I’ve tried to add the

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

wc_product_cat_class( '', $category );

and the

wc_product_class( '', $product ); 

in the cart.php template file. Neither really did what I hoped for. Any suggestions or options for other solutions?

>Solution :

There is no need to overwrite/modify template files. You can use the woocommerce_cart_item_class hook and has_term()

The table row (<tr>) will contain an extra class, based on the product category

So you get:

function filter_woocommerce_cart_item_class( $string, $cart_item, $cart_item_key ) {
    // Specific categories: the term name/term_id/slug. Several could be added, separated by a comma
    $categories_1 = array( 63, 15, 'categorie-1' );
    $categories_2 = array( 'categorie-2' );
    
    // Has term (product category)
    if ( has_term( $categories_1, 'product_cat', $cart_item['product_id'] ) ) {
        $string = 'my-class';
    } elseif ( has_term( $categories_2, 'product_cat', $cart_item['product_id'] ) ) {
        $string = 'another-class';
    }

    return $string;
}
add_filter( 'woocommerce_cart_item_class', 'filter_woocommerce_cart_item_class', 10, 3 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading