Login with Phone number in Woocommerce WordPress

Omar Kasem
2 min readDec 24, 2019

We will learn today how can we enable our customers to login with their phone number or any other custom field of our choice.

1- Add phone number field in the woocommerce registration form

The woocommerce registration form
function wooc_add_phone_number_field() {
return apply_filters( 'woocommerce_forms_field', array(
'wooc_user_phone' => array(
'type' => 'text',
'label' => __( 'Phone Number', ' woocommerce' ),
'placeholder' => __( 'Your phone number', 'woocommerce' ),
'required' => true,
),
) );
}
add_action( 'woocommerce_register_form', 'wooc_add_field_to_registeration_form', 15 );
function wooc_add_field_to_registeration_form() {
$fields = wooc_add_phone_number_field();
foreach ( $fields as $key => $field_args ) {
woocommerce_form_field( $key, $field_args );
}
}

2- Save the phone number field in the database when the user registers into the website

add_action( 'woocommerce_created_customer', 'wooc_save_extra_register_fields' );
function wooc_save_extra_register_fields( $customer_id ) {
if (isset($_POST['wooc_user_phone'])){
update_user_meta( $customer_id, 'wooc_user_phone', sanitize_text_field( $_POST['wooc_user_phone'] ) );
}
}

3- Now we need to edit the WordPress authentication process so we can tell it to login the user with his phone number or any custom field

Make a function to search for users by phone number

function wooc_get_users_by_phone($phone_number){
$user_query = new \WP_User_Query( array(
'meta_key' => 'wooc_user_phone',
'meta_value' => $phone_number,
'compare'=> '='
));
return $user_query->get_results();
}

Then we check if the email and username doesn’t exist in the authentication process, that’s how we know the user might have written his phone number, so we search for him by his phone number and return the user.

add_filter('authenticate','wooc_login_with_phone',30,3);
function wooc_login_with_phone($user, $username, $password ){
if($username != ''){
$users_with_phone = wooc_get_users_by_phone($username);
if(empty($users_with_phone)){
return $user;
}
$phone_user = $users_with_phone[0];

if ( wp_check_password( $password, $phone_user->user_pass, $phone_user->ID ) ){
return $phone_user;
}
}
return $user;
}

4- Finally we need to edit the login label to tell the user that he can login with his phone number

add_filter( 'gettext', 'wooc_change_login_label', 10, 3 );
function wooc_change_login_label( $translated, $original, $domain ) {
if ( $translated == "Username or email address" && $domain === 'woocommerce' ) {
$translated = "Username or email address or phone";
}
return $translated;
}

Full Gist of the code are here

--

--