If you want to incentivize customers to spend more in order to qualify for free shipping, or to make sure customers only pay for shipping if it’s absolutely necessary, you may find this snippet useful.
This snippet of code is a WordPress filter that hides all other shipping methods when free shipping is available on a WooCommerce stores. The function checks if the shipping method is “free_shipping”, and if so, it adds the rate to an array. If the array is not empty, the filter returns the array, otherwise, the filter returns the rates. in which cases can this snippet be used and why? This snippet can be used when a WooCommerce store needs to hide all other shipping methods when free shipping is available. This is useful for stores that want to incentivize customers to spend more in order to qualify for free shipping, or for stores that want to make sure customers only pay for shipping if it’s absolutely necessary.
add_filter( 'woocommerce_package_rates', __NAMESPACE__ . '\\codeart_hide_shipping_when_free_is_available', 100 );
function codeart_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;
}
}
return ! empty( $free ) ? $free : $rates;
}