Junes
Junes

Reputation: 47

Force free shipping without hiding all other Shipping options in WooCommerce

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:

Upvotes: 1

Views: 1964

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

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.

Upvotes: 1

Related Questions