Woocommerce - Hide other shipping methods if free shipping is available not working properly

102 Views Asked by At

im trying hide other shipping methods when free delivery is activated but when im adding two different products it shoes all possible shipping methods instead of free delivery only.

When I'm adding a product more than 50euro it's working good but when im adding more than one product it's not working.

add_filter( 'woocommerce_package_rates', 'cssigniter_hide_other_methods_when_free_shipping_is_available', 100 );
function cssigniter_hide_other_methods_when_free_shipping_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;
}
1

There are 1 best solutions below

1
GoncaloN On

It seems like your code is correctly filtering out other shipping methods when free shipping is available, but the issue arises when there are multiple products in the cart.

Check out this alternative:


    add_filter( 'woocommerce_package_rates', 'cssigniter_hide_other_methods_when_free_shipping_is_available', 100 );
    function cssigniter_hide_other_methods_when_free_shipping_is_available( $rates ) {
        $is_free_shipping_available = false;
        foreach ( $rates as $rate ) {
            if ( 'free_shipping' === $rate->method_id ) {
                $is_free_shipping_available = true;
                break;
            }
        }
    
        if ( $is_free_shipping_available ) {
            $cart_subtotal = WC()->cart->subtotal;
            $free_shipping_threshold = 50; // Adjust this value as needed
    
           if ( $cart_subtotal >= $free_shipping_threshold ) {
                $free = array();
                foreach ( $rates as $rate_id => $rate ) {
                    if ( 'free_shipping' === $rate->method_id ) {
                        $free[ $rate_id ] = $rate;
                        break;
                    }
                }
                return ! empty( $free ) ? $free : $rates;
            }
        }
    
        return $rates;
    }

This code will first check if free shipping is available. If it is, it will then check if the cart subtotal is above the threshold. If both conditions are met, it will keep only the free shipping method; otherwise, it will return all available shipping rates. Make sure to play around with the $free_shipping_threshold variable according to your own needs.

LMK if this helped.