phpwordpresswoocommerce

Display "Free Shipping" for WooCommerce Cart Products with Zero Shipping Cost


I'm trying to display "Free Shipping" for products in the WooCommerce cart that have a shipping cost of 0. I am using Webiwork Shipping Per Product WooCommerce plugin to add per-product shipping, and I want to show this message only for those products, while leaving products with non-zero shipping charges unchanged, like this screenshot:

like this screenshot

I attempted to use the following code:

add_action('woocommerce_after_cart_item_name', 'display_free_shipping_for_cart_items', 20, 2);
function display_free_shipping_for_cart_items($cart_item, $cart_item_key) {
    $packages = WC()->shipping->get_packages();

    foreach ($packages as $package) {
        if (isset($package['contents'][$cart_item_key])) {
            $product = $package['contents'][$cart_item_key];

            if (!empty($package['rates'])) {
                $shipping_rate = reset($package['rates']);
                $shipping_cost = $shipping_rate->cost;

                if ($shipping_cost == 0) {
                    echo '<p class="product-shipping-cost">Free Shipping</p>';
                }
            }
        }
    }
}

But it seems to either show nothing or doesn’t work as expected.


Solution

  • Few steps here to make it happen safely.

    1. define free shipping class, with known slug: setting shipping class

    2. set the shipping class on your product: setting shipping class to product

    add this code, that adds the title after the price on cart page, but you can adjust the hook to the wanted location:

    <?php 
    
    // Add 'Free Shipping' text after price if the product has a specific shipping class
    add_filter('woocommerce_cart_item_price', 'add_free_shipping_text_to_cart_item', 10, 3);
    
    function add_free_shipping_text_to_cart_item($price_html, $cart_item, $cart_item_key)
    {
        // Define the shipping class slug for free shipping
        $free_shipping_class_slug = 'free-shipping';
        // Get the product object
        $product = $cart_item['data'];
        $is_free_shipping = $product->get_shipping_class() == $free_shipping_class_slug;
        // Check if the product has the specified shipping class
        if ($is_free_shipping) {
            // Append "Free Shipping" text after the price
            $price_html .= '<span class="free-shipping-text">Free Shipping</span>';
        }
    
        return $price_html;
    }