Actually I want customers to add unique-phone numbers in the billing address of woo-commerce. if any tries to add / update already existed phone numbers then it should throw an error.
I tried the below code but it is not working. Can anyone give me the correct solution for unique phone numbers in the Woocommerce billing address?
add_filter( 'update_user_meta', 'ts_unique_wc_phone_field');
function ts_unique_wc_phone_field( $errors ) {
if ( isset( $_POST['billing_phone'] ) ) {
$hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);
if ( !empty($hasPhoneNumber)) {
$errors->add( 'billing_phone_error', __( '<strong>Error</strong>: Mobile number is already used!.', 'woocommerce' ) );
}
}
return $errors;
}
2
Answers
Your
get_users
call is wrong. UseCareful: you did not mention your meta key in your post. This might be something else than ‘billing_phone’. Adapt it as necessary.
This will however allow users to do shenanigans like adding a space/-/+ or something like that to the phone number, reusing it. This might need a function to filter out redundant characters upon meta value insertion, and apply the same function to
$_POST['billing_phone']
before the meta query for get_users.I have setup on one of my sites the same code within two (2) functions – one for woocommerce -> my account, and one at the checkout which checks for validity of the phone number provided specific to my country, and the other to check if the phone number already exists.
As I want to save all phone numbers as 0412345678 (no spaces) and some people enter phone numbers as 0412 345 678, the str_replace() removes this prior to saving.
While I have not tested this next part yet, and this example is referenced from this link, if you are wanting to update the admin user area you may want to use something like this.
Below is a screenshot of the results of trying to change my phone number to one that already exists while in the woocommerce->my account section.