It’s not unusual for users to forget the username they chose when signing up for a WordPress site.

Or, when registering for a site, a user might discover the username they want is already taken.

Fortunately, you can give users the option to login to your site with their email address, which they are less likely to forget.

In today’s Weekend WordPress Project, I’ll show you a couple of methods – a code snippet and a plugin – to help you easily add email login to your site.

Adding Email Login with Code

The first thing we need to do is remove the default authentication rights. Add the following snippet to your functions.php file:

//remove wordpress authentication
remove_filter(‘authenticate’, ‘wp_authenticate_username_password’, 20);

Next, we’re going to add our own authentication. To do so, we’re going to useadd_filter.

Add the following code to your functions.php files:

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->add(’empty_username’, __(‘<strong>ERROR</strong>: Email field is empty.’));
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email
$error->add(‘invalid_username’, __(‘<strong>ERROR</strong>: Email is invalid.’));
}
if(empty($password)){ //No password
$error->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->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->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add(‘invalid’, __(‘<strong>ERROR</strong>: Either the email or password you entered is invalid.’));
return $error;
}else{
return $user; //passed
}
}
}, 20, 3);

Here’s how it works:

The code checks if the username (now email) or password fields are empty. If neither are empty, it uses get_user_by to look for the user’s email. After finding a valid user, it then checks if the password is correct using thewp_check_password() function.

Adding Email Login with Plugins

WP Login Email
The WP Login Email even updates the text on the login page of your site.

If you would rather not mess around with code, the WP Email Login plugin offers a tidy solution.

Simply install the plugin and it will work off the bat. It doesn’t include any settings, it just works.

WP Email Login is available for free in the WordPress Plugin Repository and is compatible with WordPress 4.1.

It also works great (after testing) with Multisite and BuddyPress.

 

Reference: wpmudev