I currently have wordpress/woocommerce and a billing_phone valiation function (provided below) which works within the My Account -> Account Details, Checkout, etc. This function firstly checks if the value is a valid phone number, and then checks if that phone number already exists. This is a very important function in my plugin as I cannot afford to have duplicates.
I require the same checks/balances as the front end in the backend… Where I am having problems is in locating the most appropriate hook or group of hooks to allow me to validate the billing_phone field within the admin area and 1) Display the error using error message you would normally see in the admin backend, and 2) Not update the field and show the error.
I have tried user_profile_update_errors
– alas it only provides the error AFTER it has updated the meta and I cannot find any information on how to include checks within the $error
variable. I also tried edit_user_profile_update
and show_user_profile
but I don’t know how to add errors to the below function.
function user_admin_validate_billing_phone() {
if ( isset( $_POST['billing_phone'] ) && !empty( $_POST['billing_phone'] ) ) {
if ( !preg_match('/^04[0-9]{8}$/D', str_replace(' ', '', $_POST['billing_phone'] ) ) ) {
// Error: Billing Phone Number is Invalid.
}
$existing_billing_phone = get_users( 'meta_value=' . str_replace(' ', '', $_POST['billing_phone'] ) );
$current_user = wp_get_current_user();
if ( !empty( $existing_billing_phone ) ) {
if ( $current_user->billing_phone != str_replace(' ', '', $_POST['billing_phone'] ) ) {
// Error: Billing Phone Number Already Exists.
}
else {
return;
}
}
}
}
As stated, I have attempted the following hooks:
add_action( 'show_user_profile', 'user_admin_validate_billing_phone', 90 );
add_action( 'edit_user_profile', 'user_admin_validate_billing_phone', 90 );
add_action( 'personal_options_update', 'user_admin_validate_billing_phone' );
add_action( 'edit_user_profile_update', 'user_admin_validate_billing_phone' );
add_action( 'user_profile_update_errors, 'user_admin_validate_billing_phone', 10, 3 );
…however either the error comes up and the fields still change, or I don’t know how to carry over the appropriate error handling, eg:
$error = new WP_Error();
$error->add( 'error', __( 'Billing Mobile Phone Number already exists.' ) );
Any assistance, or guidance to the right process would be most appreciated.
3
Answers
Use This code.
Hope this help.
A example
Code goes in functions.php file of your active child theme (or theme). Or also in any plugin PHP files.
Please Note: By default WooCommerce use billing_phone field to take phone number, but if you have customized it then you can replace billing_phone with your field name.
Hope this helps!