In WooCommerce checkout blocks, you have the basic validation set when an email is not entered or when entering an incorrect email address. However, in some cases, store owners may want to restrict the purchase of certain products to specific email domains, such as email domains of a specific organization or company partners, etc. Let’s consider an example where a company might offer exclusive discounts on software licenses to employees using their corporate email addresses.
In this guide, we’ll show you how to automatically block purchases in checkout blocks page unless the customer uses an email address from a predefined domain.
Solution: Add Custom Validation on Email Domains in WooCommerce Checkout Blocks Page
The code ensures that if a specific product (ID 2269) is in the cart, the customer must use an email address with a required domain (tychesoftwares.com
). If not, the checkout process is blocked with an error.
add_action( 'woocommerce_store_api_checkout_update_order_from_request', function( $order, $request ) { $cart = WC()->cart->get_cart(); $required_product_id = 2269; // Replace with your required product ID $email_domain = 'tychesoftwares.com'; // Replace with the required email domain $product_found = false; // Check if the required product is in the cart foreach ( $cart as $cart_item ) { if ( $cart_item['product_id'] == $required_product_id ) { $product_found = true; break; } } // Get the customer email from the request $billing_email = isset( $request['billing_address']['email'] ) ? sanitize_email( $request['billing_address']['email'] ) : ''; // Extract domain from email $email_parts = explode( '@', $billing_email ); $customer_domain = isset( $email_parts[1] ) ? $email_parts[1] : ''; // Validation: If the required product is in the cart, enforce the email check if ( $product_found && $customer_domain !== $email_domain ) { throw new Exception( __( 'To purchase this product, you must use an email address ending in @' . $email_domain, 'woocommerce' ) ); } }, 10, 2 );
Output
When a customer attempts to place an order, the code checks whether a specific product (e.g., ID 2269) is in the cart. If the product is found, the system verifies the customer’s email domain.
Since we have defined the domain name as ‘tychesoftwares.com’ in the code, the checkout will only be allowed if the customer enters an email address ending with @tychesoftwares.com.
Solution: Add Custom Validation on Email Domains in WooCommerce Classic Checkout Page
This code applies the same logic as discussed above but performs the validation in classic checkout page.
By implementing this restriction, store owners can ensure that only eligible customers with specific email domains can proceed with their purchases. If you’re looking to further customize your checkout experience, you can also add additional custom fields in the checkout blocks page to collect extra information from customers.