To add custom validation on the WooCommerce checkout page for the first and last names to contain only letters, you can use the `woocommerce_after_checkout_validation` filter hook. This hook allows you to perform custom validation on the submitted checkout data before processing the order.
Here’s how you can add the custom validation:
1. Open your theme’s `functions.php` file or a custom plugin file.
2. Add the following code to implement the validation:
function custom_validate_checkout_names($fields, $errors) { // Validate First Name if (isset($_POST['billing_first_name']) && !preg_match('/^[A-Za-z]+$/', $_POST['billing_first_name'])) { $errors->add('billing_first_name', __('First name must contain only letters.', 'text-domain')); } // Validate Last Name if (isset($_POST['billing_last_name']) && !preg_match('/^[A-Za-z]+$/', $_POST['billing_last_name'])) { $errors->add('billing_last_name', __('Last name must contain only letters.', 'text-domain')); } return $fields; } add_filter('woocommerce_after_checkout_validation', 'custom_validate_checkout_names', 10, 2);
In this code, we use the `woocommerce_after_checkout_validation` filter hook to add our custom validation function `custom_validate_checkout_names`.
The `custom_validate_checkout_names` function checks the submitted first and last names for containing only letters. We use the `preg_match` function with a regular expression pattern (`’/^[A-Za-z]+$/’`) to validate that the names contain only letters (both uppercase and lowercase).
If the validation fails for either the first or last name, we add an error to the WooCommerce checkout object using the `$errors->add()` method. The error message will be displayed on the checkout page.
3. Save the changes, and now, when customers try to submit the checkout form with non-letter characters in the first or last name fields, an error message will appear, instructing them to enter valid names containing only letters.
Remember that this custom validation only takes place on the client side, so it’s a good practice to implement similar validation on the server-side as well. However, the client-side validation helps provide real-time feedback to users and enhances the user experience on the checkout page.