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 );
My Answer:
You have a typo in your code where you are checking the shipping country. You have misspelled the variable name `$shipping_counrtry` instead of `$shipping_country`.
Here is the corrected code:
php
function nd_hide_shipping_when_free_is_available( $rates ) {
$shipping_country = 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 );
This should now correctly hide only the Normal Shipping method when the shipping country is 'US' and cart total is more than 100.
Rate this post
4 of 5 based on 4932 votesComments