Paulund
2014-11-25 #wordpress

Login To WordPress With Email Address

By default WordPress will assign unique usernames to all users registered on the website. As they are unique there could be a possibility that the username the user wants to use is already taken so they have to use a username that they might not remember. If they don't remember their username then it can be hard for them to login in, the following code snippet will make it so your users can login using their email assigned to the user account. We need to use the action wp_authenticate which is ran before WordPress tries to authenticate the user, from here we can change the username and password submitted by the user. Inside this function we then take the $username (which is the username submitted by the login form), we can then take this value and search for a user's email. If this returns a user object then we can change the username with the username from the discovered user object.


add_action( 'wp_authenticate', 'email_address_login' );

function email_address_login( &$username, &$password )
{
    $user = get_user_by( 'email', $username );

    if( !empty( $user->user_login ) )
    {
        $username = $user->user_login;
    }
}

It's important to note that this works differently to other WordPress actions by sending the parameters as reference. Which means that this action will be better suited in the core code as a filter as it requires you to take parameters, change the values and return them. As this is an action it passes the parameters by reference which is defined by the ampersand in the function parameter list. This means that you do not need to return any values from this function you simply need to change the value of the variables and they will be returned automatically by the function. You can see how WordPress does this by looking at the core code of where wp_authenticate is ran. Inside the file /wp-includes/user.php on line 54 you will see the code


do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );

Normally when an action is called it will use the do_action() function, but this one uses the do_action_ref_array() function and passes the values by reference. I've seen many articles about this code snippet which do not pass the parameters by reference and will return the new username, this will not work as you can see from the core code of how WordPress expects this function to run.

WordPress 4.5

If you're on the newest version on WordPress 4.5 then the above functionality is built into the core, by using the function wp_authenticate_email_password()