In this guide, we'll walk you through a valuable customization for your WooCommerce Checkout page. We'll show you how to prevent customers from placing orders with PO Box addresses, ensuring smoother order processing and delivery. By implementing the provided code snippet, you can optimize both the Native Checkout and Express Checkout options in your WooCommerce store.
Blocking PO Box Addresses: The Code Snippet
To improve your WooCommerce Checkout process and prevent orders with PO Box addresses, use the following code snippet. This snippet works seamlessly with both Native Checkout and Express Checkout.
Method 1: Manually Inserting the Snippet
/**
* @snippet Disallow Shipping to PO BOX
*/
add_action( 'woocommerce_after_checkout_validation', 'peachpay_disallow_pobox_shipping' );
function peachpay_disallow_pobox_shipping( $posted ) {
$address = ( isset( $posted['shipping_address_1'] ) ) ? $posted['shipping_address_1'] : $posted['billing_address_1'];
$address2 = ( isset( $posted['shipping_address_2'] ) ) ? $posted['shipping_address_2'] : $posted['billing_address_2'];
$postcode = ( isset( $posted['shipping_postcode'] ) ) ? $posted['shipping_postcode'] : $posted['billing_postcode'];
$replace = array( " ", ".", "," );
$address = strtolower( str_replace( $replace, '', $address ) );
$address2 = strtolower( str_replace( $replace, '', $address2 ) );
$postcode = strtolower( str_replace( $replace, '', $postcode ) );
if ( strstr( $address, 'pobox' ) || strstr( $address2, 'pobox' ) || strstr( $postcode, 'pobox' ) ) {
wc_add_notice( 'Sorry, we do not ship to PO BOX addresses.', 'error' );
}
}
To manually insert the code snippet, follow these steps:
functions.php
file for editing.Method 2: Using a Plugin for Hassle-Free Integration
If you prefer a user-friendly approach, you can use a plugin to insert code snippets. One recommended plugin is "Code Snippets," which allows you to manage and execute code snippets without directly editing theme files. You can install it from the WordPress Plugin repository.
Error Notification:
Should a customer attempt to use a PO Box address during checkout, they will encounter a user-friendly error message that informs them of the restriction. Here's a screenshot of how the error message will appear: