WordPress woocommerce – hide other shipping method when flat rate available

It’s easy to find how to hide other shipping methods when free shipping is available. But I would like to hide other shipping methods when flat rate is available (I have custom other methods).

Can you help please ?

Read More

regards

Related posts

Leave a Reply

1 comment

  1. The code below is modified from this article :

    add_filter('woocommerce_package_rates', 'xa_hide_shipping_rates_when_flat_rate_is_available', 10, 2);
    function xa_hide_shipping_rates_when_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;
    }
    

    I am not sure which WooCommerce version you are using but I have tested for version 2.6 but not the versions before it.