Select the Cheapest Shipping Method by Default
Preselects the lowest-priced shipping option for new carts instead of whichever method happens to be first in the zone.
Opens WPIDE on
Code
add_filter( 'woocommerce_shipping_chosen_method', function ( $default, $rates, $chosen ) {
if ( $chosen && isset( $rates[ $chosen ] ) ) {
return $chosen;
}
$cheapest = $default;
$lowest = null;
foreach ( $rates as $id => $rate ) {
$cost = (float) $rate->get_cost();
if ( null === $lowest || $cost < $lowest ) {
$lowest = $cost;
$cheapest = $id;
}
}
return $cheapest;
}, 10, 3 );
Notes
Only sets the default; a method the customer picks themselves is kept.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.