1
votes

In Woocommerce, we use the following code to hide all shipping methods except free shipping:

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 );

Now we would like to keep Express shipping as well as local pickup. Free shipping, however, should be preselected.

Does anyone have an idea how we can customize the code?

Our Shipping methods rate Ids are:

  • Normal delivery (Versandkosten): legacy_flat_rate
  • Express delivery (Expressversand): legacy_flat_rateexpress
  • Free shipping (kostenloser Versand): legacy_free_shipping
  • Local Pickup (Abholung vor Ort): legacy_local_pickup
1
thank you very much. I added the details in my first post.Junes
I have edited your question with the correct working Shipping methods IDs that are required (it has to be the value of the <input> fields, but not the tag Id)LoicTheAztec

1 Answers

1
votes

To hide Normal delivery only, when "Free shipping" is available, you will need something different:

add_filter( 'woocommerce_package_rates', 'show_hide_shipping_methods', 100 );
function show_hide_shipping_methods( $rates ) {
    // When "Free shipping" is available
    if( isset($rates['legacy_free_shipping']) && isset($rates['legacy_flat_rate']) ) {
        // Hide normal flat rate
        unset($rates['legacy_flat_rate']);
    }
    return $rates;
}

The following will set "Free shipping" as default chosen shipping method:

add_filter( 'woocommerce_shipping_chosen_method', 'set_default_chosen_shipping_method', 10, 3 );
function set_default_chosen_shipping_method( $default, $rates, $chosen_method ) {
    if( isset($rates['legacy_free_shipping']) ) {
        $default = 'legacy_free_shipping';
    }
    return $default;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Refresh the shipping caches: (required)

  1. This code is already saved on your active theme's function.php file.
  2. The cart is empty
  3. In a shipping zone settings, disable / save any shipping method, then enable back / save.