Created
May 7, 2025 06:12
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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