Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add CSS class(es) to WooCommerce cart items with (or based on) product categories

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

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?

like image 827
BeTA iT Avatar asked Nov 15 '25 17:11

BeTA iT


1 Answers

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 );

OR to add the term slugs as CSS class(es) instead, so you don't have to specify it via an if condition:

function filter_woocommerce_cart_item_class( $string, $cart_item, $cart_item_key ) {
    // Get the product categories slugs for this item
    $term_slugs = wp_get_post_terms( $cart_item['product_id'], 'product_cat', array( 'fields' => 'slugs' ) );

    // NOT empty
    if ( ! empty ( $term_slugs ) ) {
        $string = implode( ' ', $term_slugs );
    }

    return $string;
}
add_filter( 'woocommerce_cart_item_class', 'filter_woocommerce_cart_item_class', 10, 3 );
like image 192
7uc1f3r Avatar answered Nov 17 '25 10:11

7uc1f3r