WP SITES

3085 Coded Tutorials & 288 Plugins

Free Shipping Per Product – WooCommerce

This PHP code checks if the product id is in cart and if so, removes all other shipping methods leaving free shipping as the selected option. If no free shipping method has been added to the zone, it creates one.

add_filter( 'woocommerce_package_rates', 'wpsites_show_only_free_shipping_for_specific_product', 20, 2 );
function wpsites_show_only_free_shipping_for_specific_product( $rates, $package ) {
    $target_product_id = 6455; // 🔹 Replace with your product ID
    $product_in_cart   = false;

    // Check if the target product is in the cart
    foreach ( $package['contents'] as $item ) {
        if ( $item['product_id'] == $target_product_id ) {
            $product_in_cart = true;
            break;
        }
    }

    // If the product is in the cart → remove all shipping methods except free shipping
    if ( $product_in_cart ) {
        $free_shipping_available = false;

        // Keep only free shipping if it already exists
        foreach ( $rates as $rate_id => $rate ) {
            if ( 'free_shipping' !== $rate->method_id ) {
                unset( $rates[$rate_id] );
            } else {
                $free_shipping_available = true;
            }
        }

        // If no free shipping method exists in the zone, create one dynamically
        if ( ! $free_shipping_available ) {
            $rates = array();
            $rates['custom_free_shipping'] = new WC_Shipping_Rate(
                'custom_free_shipping',
                __( 'Free shipping', 'woocommerce' ),
                0,
                array(),
                'custom_free_shipping'
            );
        }
    }

    return $rates;
}

The reason you need to use this code rather than the shipping settings is because shipping methods do not enable you to add shipping classes.

Code Installation

Add the code to the end of your child themes functions file or code snippets plugin.

Usage

Swap out the product ID 6455 on line 3 of the code to match your free shipping product.

Free Shipping & Custom Shipping Labels Plugin

This plugin enables you to assign free shipping per product and taxonomy term. You can also customize the shipping label per product and per term as well.

Leave a Reply

New Plugins