Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shameemreza/a11a54c82eed7214082671f1299e7c72 to your computer and use it in GitHub Desktop.
Save shameemreza/a11a54c82eed7214082671f1299e7c72 to your computer and use it in GitHub Desktop.
WooCommerce Distance Rate Shipping: Filter to only return the shipping rate with the lowest cost when multiple rates are available.
add_filter( 'woocommerce_package_rates', 'keep_only_lowest_distance_rate', 20, 2 );
function keep_only_lowest_distance_rate( $rates, $package ) {
$lowest_rate_key = '';
$lowest_cost = null;
foreach ( $rates as $rate_key => $rate ) {
if ( is_null( $lowest_cost ) || floatval( $rate->cost ) < $lowest_cost ) {
$lowest_cost = floatval( $rate->cost );
$lowest_rate_key = $rate_key;
}
}
// Keep only the cheapest one
foreach ( $rates as $rate_key => $rate ) {
if ( $rate_key !== $lowest_rate_key ) {
unset( $rates[ $rate_key ] );
}
}
return $rates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment