Accept Orders Only for Your Delivery Area
Stops checkout with a friendly message when the delivery postcode is outside the area you serve, ideal for local food, flower or furniture delivery.
Opens WPIDE on
Code
$wpide_area_postcodes = array( 'SW1*', 'SW3*', 'W8*' ); // Postcodes or prefixes ending in *.
$wpide_area_message = 'Sorry, we only deliver within central London at the moment.';
add_action( 'woocommerce_after_checkout_validation', function ( $data, $errors ) use ( $wpide_area_postcodes, $wpide_area_message ) {
if ( empty( WC()->cart ) || ! WC()->cart->needs_shipping() ) {
return;
}
$prefix = ! empty( $data['ship_to_different_address'] ) ? 'shipping_' : 'billing_';
$postcode = strtoupper( str_replace( ' ', '', (string) ( $data[ $prefix . 'postcode' ] ?? '' ) ) );
foreach ( $wpide_area_postcodes as $rule ) {
$rule = strtoupper( str_replace( ' ', '', $rule ) );
if ( '*' === substr( $rule, -1 ) ? 0 === strpos( $postcode, rtrim( $rule, '*' ) ) : $postcode === $rule ) {
return;
}
}
$errors->add( 'shipping', esc_html( $wpide_area_message ) );
}, 10, 2 );
Notes
Postcodes ending in * match by prefix, and orders that do not need shipping are never checked.
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.