Offer a Shipping Method Only to Listed Postcodes
Shows a method such as local delivery or same-day courier only when the shipping postcode matches your list or starts with one of your prefixes.
Opens WPIDE on
Code
$wpide_local_rate_id = 'flat_rate:3'; // Rate ID to restrict.
$wpide_local_postcodes = array( '10115', '10117', '101*' ); // Exact postcodes or prefixes ending in *.
add_filter( 'woocommerce_package_rates', function ( $rates, $package ) use ( $wpide_local_rate_id, $wpide_local_postcodes ) {
if ( ! isset( $rates[ $wpide_local_rate_id ] ) ) {
return $rates;
}
$postcode = strtoupper( str_replace( ' ', '', (string) ( $package['destination']['postcode'] ?? '' ) ) );
$allowed = false;
foreach ( $wpide_local_postcodes as $rule ) {
$rule = strtoupper( str_replace( ' ', '', $rule ) );
if ( '*' === substr( $rule, -1 ) ? 0 === strpos( $postcode, rtrim( $rule, '*' ) ) : $postcode === $rule ) {
$allowed = true;
break;
}
}
if ( '' === $postcode || ! $allowed ) {
unset( $rates[ $wpide_local_rate_id ] );
}
return $rates;
}, 20, 2 );
Notes
Use the rate ID shown in WooCommerce > Settings > Shipping (for example flat_rate:3); postcodes ending in * match by prefix.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.