Monday , December 30 2024

How to Hide Other Shipping Methods When Free Shipping is Available in WooCommerce

In WooCommerce, you may offer free shipping to your customers when they purchase items above a certain amount. However, you may also have other shipping methods available that customers can choose from. If you want to ensure that customers can only select the free shipping option when it is available, you can use a simple code snippet.

First, open the functions.php file of your active theme or create a custom plugin. Then, add the following code to the file:

add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );

function hide_shipping_when_free_is_available( $rates, $package ) {

  $free_shipping_available = false;

  // Check if free shipping is available
  foreach ( $rates as $rate_id => $rate ) {
    if ( 'free_shipping' === $rate->method_id ) {
      $free_shipping_available = true;
      break;
    }
  }

  // If free shipping is available, hide other shipping methods
  if ( $free_shipping_available ) {
    foreach ( $rates as $rate_id => $rate ) {
      if ( 'free_shipping' !== $rate->method_id ) {
        unset( $rates[ $rate_id ] );
      }
    }
  }

  return $rates;
}

OR

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 );

This code uses the woocommerce_package_rates filter to modify the available shipping rates based on whether free shipping is available or not. The code first checks if free shipping is available by iterating through the shipping rates and checking if there is a rate with the method_id of ‘free_shipping’. If free shipping is available, the code loops through the shipping rates again and removes any rate that is not free shipping.

To achive this i added 2 shipping method in my shipping Zone. Flat rate and Free shipping. Free shipping is only avaliable when users spend this amount to get free shipping

Minimum order amount

spend amount to get free shipping

In conclusion, hiding other shipping methods when free shipping is available is a great way to provide a seamless shopping experience for your customers. By using this code snippet, you can ensure that your customers are always aware of the free shipping option and can take advantage of it when it is available.

Check Also

How to remove WordPress REST API links without Plugin

What is the WordPress REST API? The WordPress REST API is a programming interface that …

Leave a Reply

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