user3766894
user3766894

Reputation: 73

Add a custom text to WooCommerce cart items if the product has a specific shipping class

I'm trying to display a specific text below the product title on the checkout / cart page when a product has a specific shipping class. How do I do that?

I'm having a hard time adding text inside the product loop.

Upvotes: 2

Views: 5398

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253959

The following will display a custom text under the cart item name in cart and checkout pages for a defined shipping class:

// 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 = 'extra';

    if( is_cart() && $cart_item['data']->get_shipping_class() === $shipping_class ) {
        $item_name .= '<br /><div class="item-shipping-class">' . __("This is my custom text", "woocommerce") . '</div>';
    }
    return $item_name;
}

// Display a custom text under cart item name in checkout
add_filter( 'woocommerce_checkout_cart_item_quantity', 'custom_checkout_text_cart_item_name', 10, 3 );
function custom_checkout_text_cart_item_name( $item_qty, $cart_item, $cart_item_key ) {
    // Here below define your shipping class slug
    $shipping_class = 'extra';

    if( $cart_item['data']->get_shipping_class() === $shipping_class ) {
        $item_qty .= '<br /><div class="item-shipping-class">' . __("This is my custom text", "woocommerce") . '</div>';
    }
    return $item_qty;
}

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

Upvotes: 5

Related Questions