Matt A
Matt A

Reputation: 43

Display custom texts based on shipping classes in WooCommerce cart

Here is what I have and it works great for 1 shipping class, but want to have separate messages for different shipping classes:

// Display a custom text under cart item name in cart page
add_filter( 'woocommerce_cart_item_name', 'custom_text_cart_item_name', 10, 3 );
function custom_text_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
// Here below define your shipping class slug
$shipping_class = '5-gallon';

if( is_cart() && $cart_item['data']->get_shipping_class() === $shipping_class ) {
    $item_name .= '<br /><div class="item-shipping-class">' . __("Please call confirm shipping rates", "woocommerce") . '</div>';
}
return $item_name; }

Upvotes: 3

Views: 461

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253969

For multiple shipping classes with different messages you can use the following:

// Display a custom text under cart item name in cart page
add_filter( 'woocommerce_cart_item_name', 'custom_text_cart_item_name', 10, 3 );
function custom_text_cart_item_name( $item_name, $cart_item, $cart_item_key ) {
    // Only on cart page
    if( ! is_cart() ) 
        return $item_name;

    // Here below define your shipping classes slugs (one by line)
    $shipping_class_1 = '5-gallon';
    $shipping_class_2 = '10-gallon';

    $shipping_class   = $cart_item['data']->get_shipping_class();

    // First shipping class
    if( $shipping_class === $shipping_class_1 ) {
        $item_name .= '<br /><div class="item-shipping-class">' . __("Please call confirm shipping rates", "woocommerce") . '</div>';
    }
    // 2nd shipping class
    elseif( $shipping_class === $shipping_class_2 ) {
        $item_name .= '<br /><div class="item-shipping-class">' . __("Some different message…", "woocommerce") . '</div>';
    }

    return $item_name; 
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Upvotes: 2

Related Questions