WooCommerce default to free shipping or legacy free shipping

Recent WooCommerce updates (starting with 2.6.0) introduced the concept of shipping zones.  You have the option to configure Shipping Zones, which will provide the standard selections like Flat Rate, Free Shipping and Local Pickup.  

In the meantime however, the existing shipping methods will be renamed with a legacy "legacy_" prefix and that can cause some of the shipping customizations to no longer work. One of those is the snippet provided by WooCommerce used to hide all other shipping methods when free shipping is available. The code relies on the shipping method using method_id of free_shipping and no longer works since the method_id has changed to legacy_free_shipping.

To support the legacy_free_shipping shipping method but also be ready for when your regions are configured you can use the following modified code (This needs to be added/replaced in functions.php).

function my_hide_shipping_when_free_is_available( $rates ) {
    $free = array();
    $legacyFree = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        } 
        if ( 'legacy_free_shipping' === $rate->method_id ) {
            $legacyFree[ $rate_id ] = $rate;
            break;
        }           
    }
    return ! empty( $free ) ? $free : (!empty($legacyFree) ? $legacyFree : $rates);
}
add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );        

The original code is here:
https://docs.woocommerce.com/document/hide-other-shipping-methods-when-free-shipping-is-available/

Leave a Reply

Your email address will not be published. Required fields are marked *