Firstly, you try to achieve free shipping if a certain product is in the cart by using shipping classes. Only implement this solution if you have exhausted native WooCommerce tools. This solution simply bypasses these rules if you have a basic store setup and don’t have a need for shipping classes. In summary, these code snippet looks at all the products in the cart, and if a particular product is found, free shipping is granted for the entire order. This type of rule could encourage users to buy a particular product from your store because there is a free shipping incentive. You will need the product ID of the product to trigger enabling of the shipping method which will be hidden. To get the product ID, go to Dashboard > Products > All Products then hover over your desired product – you will see the Product ID appear under the product name. You will also need the shipping method radio button value which is explained in more detail further on in this guide.
/**
* Snippet Name: WooCommerce free shipping if a specific product is in the cart.
* Snippet Author: ecommercehints.com
*/
add_filter( 'woocommerce_package_rates', 'ecommercehints_free_shipping_for_specific_products', 10, 2 );
function ecommercehints_free_shipping_for_specific_products($rates, $package) {
$product_id = 12; // The product ID of the product to trigger enabling of the shipping method
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if (!$in_cart ) {
unset( $rates['free_shipping:14'] ); // The shipping method radio button value
}
return $rates;
}
How Can I Get The Shipping Method Radio Button Value?
