Login to WordPress using an email address instead of username

A client recently asked me how to change the default login function in WordPress so that users access the website with their email address, instead of a username.

In short, this can be done in three steps:

  1. Remove default authentication function
  2. Add custom authentication function
  3. Change text “Username” in wp-login.php to “Email”

Note: Don’t edit core files.

1. Remove WordPress default authentication function.

WordPress uses “authenticate” filter to perform additional validation at user login.

remove_filter('authenticate', 'wp_authenticate_username_password', 20);

2. Add custom authentication function

add_filter('authenticate', function($user, $email, $password){
//Check for empty fields
if(empty($email) || empty ($password)){
//create new error object and add errors to it.
$error = new WP_Error();
if(empty($email)){ //No email
$error-&gt;add('empty_username', __('<strong>ERROR</strong>: Email field is empty.'));
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email
$error-&gt;add('invalid_username', __('<strong>ERROR</strong>: Email is invalid.'));
}
if(empty($password)){ //No password
$error-&gt;add('empty_password', __('<strong>ERROR</strong>: Password field is empty.'));
}
return $error;
}
//Check if user exists in WordPress database
$user = get_user_by('email', $email);
//bad email
if(!$user){
$error = new WP_Error();
$error-&gt;add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}
else{ //check password
if(!wp_check_password($password, $user-&gt;user_pass, $user-&gt;ID)){ //bad password
$error = new WP_Error();
$error-&gt;add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}else{
return $user; //passed
}
}
}, 20, 3);

3. Change text “Username” in wp-login.php to “Email”

We can use gettext filter to change text “Username” to “Email” without editing core files.

add_filter('gettext', function($text){
if(in_array($GLOBALS['pagenow'], array('wp-login.php'))){
if('Username' == $text){
return 'Email';
}
}
return $text;
}, 20);

No Comments

Leave a Reply