Hide other shipping method when flat rate is available in Woocommerce

I wanted to create a function for WordPress plugin Woocommerce to hide other shipping method when flat rate is available.

This is very useful when you have a generated shipping method like UPS or DHL and you have also a flat rate. For some products you can create a shipping class and select that specific rate for shipping on that product.

But the problem is when you will go to checkout you will see all shipping rates. If you wish only to have flat rate when is available then use the function bellow:

add_filter('woocommerce_package_rates', 'dexblog_hide_shipping_rates_flat_rate_is_available', 10, 2);
function dexblog_hide_shipping_rates_flat_rate_is_available($rates, $package) {
    global $woocommerce;
    $version = "2.6";
    if (version_compare($woocommerce->version, $version, ">=")) {
        foreach($rates as $key => $value) {
            $key_part = explode(":", $key);
            $method_title = $key_part[0];
            if ('flat_rate' == $method_title) {
                $flat_rate_shipping = $rates[$key];
                // Unset all rates.
                $rates = array();
                // Restore flat rate shipping rate.
                $rates[$key] = $flat_rate_shipping;
                return $rates;
            }
        }
    }
    else {
        if (isset($rates['flat_rate'])) {
            // Below code is for unsetting single shipping method/option.
            $flat_rate = $rates['flat_rate'];
            // Unset all rates.
            $rates = array();
            // Restore flat rate shipping rate.
            $rates['flat_rate'] = $flat_rate;
        }
    }

    return $rates;
}

Hope this will help you. Best wishes

One thought on “Hide other shipping method when flat rate is available in Woocommerce

  • September 14, 2020 at 6:41 am
    Permalink

    Hi,

    This code remove all shipping method, we need to exclude local pickup option. That means when flat rate shipping available it will hide all other shipping option except local pickup.

    can you help on this.

    Thanks in advance

    Reply

Leave a Reply

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

tutorials