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