Allow Users to Login with Email Address OR Username in WordPress

Screenshot 2015-09-12 16.03.39 One of my clients complained that her users were contacting her quite often because they had forgotten their username. Of course, the username is listed in the email if you click on 'forgot password', but many novice users don't know that or don't think to click there to find their username.

I figured that should be an easy fix. I found a couple of plugins quickly and installed them, but they didn't seem to change anything.

I Googled the problem, found some fixes, installed the code and still, I couldn't login with my email address.

I spent WAY more time than I'd care to admit on this one small little problem. It should be easy to allow the email address for login, so that a user can choose to use either their username OR their email address.

All the solutions I found used wp_authenticate_username_password(). After much trial and error, I found out that wp_authenticate_username_password() ignores the username and password you pass to it and uses the $_POST variables instead. I couldn't just change the post variables.

After digging around in wp-login.php, I saw that it was using wp_signon instead of wp_authenticate_username_password(). wp_signon allows me to pass the credentials as a parameter and it doesn't ignore them!

I finally figured out the hook and the code that will work:

add_action('login_init', 'authenticate_username_or_email', 10);

function authenticate_username_or_email() {
    
    $username = $_POST['log'];
    $password = $_POST['pwd'];
    
    if (filter_var($username, FILTER_VALIDATE_EMAIL)) { //Invalid Email
        $user = get_user_by('email', $username);
    } else {
	$user = get_user_by('login', $username);
    }
    
    if ($user && wp_check_password( $password, $user->data->user_pass, $user->ID)) {
        $creds = array('user_login' => $user->data->user_login, 'user_password' => $password);
        $user = wp_signon( $creds, $secure_cookie );
        wp_redirect('/members/'.$user->data->user_login.'/courses');
    }
}

/* change the label on the form to include the email address */
add_filter( 'gettext', 'addEmailToLogin', 20, 3 );

function addEmailToLogin( $translated_text, $text, $domain ) {
    if ( "Username" == $translated_text )
        $translated_text .= __( ' Or Email');
    return $translated_text;
}

If the username or email and password are invalid, then it will fall through to the core code and show the error on the form.

Disclosure: Some of the links on this site are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *