On checkout page, I am trying to disable the shipping method option according to my area postcode. You can find image here . I am working on Wordpress and PHP as a backend.
If the postcode doesnot match the area, the shipping method will be disable and the text "" will be shown here. I am using this code:
$packages = WC()->cart->get_shipping_packages();
foreach ($packages as $key => $value) {
$shipping_session = "shipping_for_package_$key";
unset(WC()->session->$shipping_session);
}
But this code is not working, It will not disable the shipping method option. Can anyone help me?
You can disable shipping methods via the woocommerce_package_rates
hook.
You can get the postcode via the second argument of the hook: $package
.
In the example below, if the postcode doesn't match one of those in the $postcodes
array, the shipping methods are disabled (you can also apply your logic in reverse, by exclusion. You can also check the state and country if needed.).
All the fields you can get through $package
are:
$package['destination']['country']
$package['destination']['state']
$package['destination']['postcode']
$package['destination']['city']
$package['destination']['address']
$package['destination']['address_1']
$package['destination']['address_2']
Then:
// disable shipping methods based on postcode
add_filter( 'woocommerce_package_rates', 'disable_shipping_method_based_on_postcode', 10, 2 );
function disable_shipping_method_based_on_postcode( $rates, $package ) {
// initialize postcodes to match
$postcodes = array( 12050, 20052, 15600, 45063 );
// if the customer's postcode is not present in the array, disable the shipping methods
if ( ! in_array( $package['destination']['postcode'], $postcodes ) ) {
foreach ( $rates as $rate_id => $rate ) {
unset( $rates[$rate_id] );
}
}
return $rates;
}
The code has been tested and works. Add it to your active theme's functions.php.
RELATED ANSWERS