Block PO Box Shipping Addresses
Rejects checkout when the shipping address is a PO Box or post office locker, for couriers that cannot deliver there.
Opens WPIDE on
Code
$wpide_po_patterns = '/\b(p\.?\s*o\.?\s*box|post\s*office\s*box|pobox|packstation|postfach)\b/i'; // Patterns to block.
add_action( 'woocommerce_after_checkout_validation', function ( $data, $errors ) use ( $wpide_po_patterns ) {
if ( empty( WC()->cart ) || ! WC()->cart->needs_shipping() ) {
return;
}
$prefix = ! empty( $data['ship_to_different_address'] ) ? 'shipping_' : 'billing_';
$lines = ( $data[ $prefix . 'address_1' ] ?? '' ) . ' ' . ( $data[ $prefix . 'address_2' ] ?? '' );
if ( preg_match( $wpide_po_patterns, $lines ) ) {
$errors->add( 'shipping', 'Sorry, we cannot deliver to PO Boxes or parcel lockers. Please enter a street address.' );
}
}, 10, 2 );
Notes
Checks both address lines of the address the order ships to; extend $wpide_po_patterns for other languages.
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.