The Free Shipping method that comes with WooCommerce is pretty flexible. What it's not great at is allowing a store to mark one or two items to use free shipping for and leave the rest of the products to use your other shipping methods. We can use the shipping classes built into WooCommerce combined with a little bit of code to mark any number of products eligible for free shipping.
In order to enable free shipping on a per product basis, go through the following steps:
Once you have a shipping class, you need to copy the shipping class Slug, which we can use to identify that shipping class in the code.
Now that we have our shipping class, we can write the code to add some extra functionality for that shipping class.
functions.php
file, which is located at wp-content/themes/your-theme-name/
or a custom WooCommerce plugin:/* * Enable free shipping for orders with products that have the free-shipping shipping class slug * * @param bool $is_available */ function woocommerce_cookbook_enable_free_shipping ( $is_available ) { global $woocommerce; // set the shipping classes that are eligible $eligible = array( 'free-shipping' ); // get cart contents $cart_items = $woocommerce->cart->get_cart(); // make sure there is something in the cart if ( is_array( $cart_items ) && count( $cart_items ) >1 ) { // loop through the items checking to make sure they all have the right class foreach ( $cart_items as $key => $item ) { if ( ! in_array( $item['data']->shipping_class, $eligible ) ) { // this item doesn't have the right class. return false return false; } } } // nothing out of the ordinary return the default value return $is_available; } add_filter( 'woocommerce_shipping_free_shipping_is_available', 'woocommerce_cookbook_enable_free_shipping', 20 );
That's it! That's all the code you'll need. The last thing we need to do is add the shipping class to our products, as shown in the following screenshot. This is explained in detail in the Creating shipping classes recipe of this chapter.
This code snippet works a bit counter-intuitively. It doesn't automatically let any product with the shipping class use free shipping. It instead prevents every other product from using free shipping. The advantage of this is that there's very little code and you can still use the free shipping settings. You could, for example, require that the user purchase $5 of goods before unlocking free shipping for your tiny items.