1
votes

I am trying to hide a shipping method on the checkout page of WooCommerce when shipping country selected is United States - 'US' and cart_total is more than 100. But the script is still hiding both the Normal Shipping and Express shipping, when it should only hide the normal shipping(flat_rate:4). Any help will be greatly appreciated!

function nd_hide_shipping_when_free_is_available( $rates ) {
    $shipping_counrtry = WC()->customer->get_shipping_country();
    $total = WC()->cart->get_displayed_subtotal();
    if ($shipping_country == "US" && $total >= 100){
        unset($rates['flat_rate:4']);
        return $rates;
    }else{
        $free = array();
        foreach ( $rates as $rate_id => $rate ) {
            if ( 'free_shipping' === $rate->method_id ) {
                $free[ $rate_id ] = $rate;
                break;
            }
        }
        return ! empty( $free ) ? $free : $rates;
    }
}
add_filter( 'woocommerce_package_rates', 'nd_hide_shipping_when_free_is_available', 100 );
1
Try to clarify your question as it's not clear… How is set you free shipping method for US and non US. how many shipping zones do you have. what are the related shipping rate Ids for US? What should happen with free shipping method when subtotal is over 100 in US?LoicTheAztec
Hi @LoicTheAztec, I have 4 shipping zones. The ID for US shipping zone is 2. The free shipping method will be displayed with the express shipping method when subtotal is over 100 in US. For the other shipping zones, only the free shipping should be displayed when subtotal is over 100.Ugene

1 Answers

2
votes

You can try the following, that will hide 'flat_rate:4' shipping method rate id for US and when cart subtotal reaches 100 or more, otherwise when free shipping is available, it will hide other shipping methods:

add_filter( 'woocommerce_package_rates', 'shipping_based_on_country_subtotal_and_free_available', 100, 2 );
function shipping_based_on_country_subtotal_and_free_available( $rates, $package ) {
    $country   = WC()->customer->get_shipping_country();
    $subtotal  = WC()->cart->subtotal; // subtotal incl taxes
    $condition = $country == "US" && $subtotal >= 100; // <== HERE Set your condition (country and minimal subtotal amount)
    $free      = array(); // Initializing

    // Loop through shipping rates for current shipping package
    foreach ( $rates as $rate_key => $rate ) {
        if ( $condition ){
            $targeted_rate_id = 'flat_rate:4';
            
            if( $targeted_rate_id === $rate_key ) {
                unset($rates[$targeted_rate_id]);
            }
        }
        elseif ( 'free_shipping' === $rate->method_id ) {
            $free[$rate_key] = $rate;
        }
    }
    return ! empty( $free ) && ! $condition ? $free : $rates;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Important: Once code is saved, empty the cart to refresh shipping rates...