Deny PO Box addresses in WooCommerce

Many of you may not want to allow Post Office Box as shipping address. There is no default option in WooCommerce to do it. We can use woocommerce_after_checkout_validation action hook to check if inputted shipping address contains PO Box address or not.

Following code checks for the string pobox in the inputted address and throws an error, when finds one.

function careless_deny_pobox( $posted ) {
    $address = ( isset( $posted['shipping_address_1'] ) ) ? $posted['shipping_address_1'] : $posted['billing_address_1'];
    $postcode = ( isset( $posted['shipping_postcode'] ) ) ? $posted['shipping_postcode'] : $posted['billing_postcode'];

    $replace = array( " ", ".", "," );
    $address = strtolower( str_replace( $replace, '', $address ) );
    $postcode = strtolower( str_replace( $replace, '', $postcode ) );

    if ( strstr( $address, 'pobox' ) || strstr( $postcode, 'pobox' ) ) {
        wc_add_notice( __( 'Sorry, we cannot ship to PO BOX addresses!' ), 'error' );
    }
}
add_action( 'woocommerce_after_checkout_validation', 'careless_deny_pobox' );

Code goes in the functions.php file of your active theme.