show only free shipping if available

WooCommerce: Show only Free shipping if Available

By default, every shipping method in a zone is shown to the customer at the checkout page. let’s see how to show only free shipping if available and hide other shipping options.

In case you only want to show free shipping method if it’s available for your customer. Maybe you offer free shipping for some products or for certain total order cost like “free shipping for $100+ shipping”.

You can add the following snippet at bottom of your functions.php or use Code snippets plugin if you are not comfortable editing theme files directly.

** Hide shipping rates when free shipping is available.
 *
 * @param array $rates Array of rates found for the package.
 * @return array
 */
function my_hide_shipping_when_free_is_available( $rates ) {
	$free = array();

	foreach ( $rates as $rate_id => $rate ) {
		if ( 'free_shipping' === $rate->method_id ) {
			$free[ $rate_id ] = $rate;
			break;
		}
	}

	return ! empty( $free ) ? $free : $rates;
}

add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );

After you add the above code snippet, Users will not see other shipping methods on the checkout page if they are eligible for free shipping.

Yes, it was that easy

HOW TO ADD PHP CODE

The Code Snippets plugin makes it very easy to not just add PHP snippets to your website but also manage all the snippets you add.

You can activate and deactivate certain snippets, and even adds notes about what they do. It even has better error handling to avoid the PHP error scenarios.

To install it, simply go to Plugins > Add New and search for Code Snippets.

The traditional or normal way to add PHP snippets to your theme is to add directly in your theme’s functions.php file.

However, make sure you are using a child theme otherwise you will lose all changes once you update your theme.


I hope this article helped you to Only show free shipping if available. Have any question? Don’t forget to leave a comment below…

If you liked this article, then please follow us on Facebook for more WooCommerce and WordPress tutorials. You can also find us on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *