Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WooCommerce - Hide shipping rates when free shipping is available.
<?php
/**
* Hide shipping rates when free shipping is available.
* Updated to support WooCommerce 2.6 Shipping Zones.
*
* @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 );
@KoolPal
Copy link

KoolPal commented Jul 29, 2022

add_filter('woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2);
function hide_shipping_when_free_is_available($rates, $package) {
$free_yn = 0;
$pickup_yn = 0;
foreach($rates as $key => $value) {
$key_part = explode(":", $key);
$method_title = $key_part[0];
if ('free_shipping' == $method_title) {
// check if free shipping rate exists
$free_yn = 1;
$free_shipping = $rates[$key];
$free_key = $key;
}
if ('local_pickup' == $method_title) {
// check if local pickup rate exists
$pickup_yn = 1;
$local_pickup = $rates[$key];
$pickup_key = $key;
}
}
if ($free_yn == 1) {
// Unset all rates.
$rates = array();
// Restore free shipping rate.
$rates[$free_key] = $free_shipping;
if ($pickup_yn == 1) {
// Restore local pickup rate.
$rates[$pickup_key] = $local_pickup;
}
return $rates;
}
return $rates;
}

@masjo Brilliant! Still works awesome in 2022! God bless you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment