In some of my client projects, there was a requirement to restrict specific shipping methods for certain postcodes. However, configuring this using WooCommerce shipping zones can sometimes become complicated and time-consuming.
So instead of making the configuration overly complicated, I decided to handle it with custom code. This approach made the solution simpler, more flexible, and easier to manage.
If you add the code below to your active theme’s functions.php file, the issue will be resolved. Try it out.
function example_disallow_shipping_by_postcodes( $rates, $package ) {
$allowed_postcodes = array( '9001', '8006' );
$restricted_shipping_method_type = 'flat_rate';
$restricted_shipping_method_id = 2;
$restricted_shipping_method = "{$restricted_shipping_method_type}:{$restricted_shipping_method_id}";
$customer_postcode = WC()->customer->get_shipping_postcode();
foreach( $rates as $rate_id => $rate ) {
if( $rate_id !== $restricted_shipping_method ) {
continue;
}
if( ! in_array( $customer_postcode, $allowed_postcodes ) ) {
unset( $rates[ $rate_id ] );
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'example_disallow_shipping_by_postcodes', 30, 2 );
Use this code and let me know in the comments if it fixes your problem.



