Hide other shipping method when flat rate is available in Woocommerce

0
366

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here