• Skip to primary navigation
  • Skip to main content

RocketGeek

Home of WP-Members, The Original WordPress Membership Plugin

  • WordPress Plugins
    • WP-Members
      • FAQs
      • Quick Start
      • Documentation
      • Extensions
    • Advanced Options
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Download Protect
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Invite Codes
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • MailChimp Integration
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • PayPal Subscriptions
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Salesforce Web-to-Lead
    • Security
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Text Editor
      • Purchase the Plugin
      • Get the Pro Bundle
    • User List
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • User Tracking
      • Documentation
      • Purchase the Plugin
      • Get the Pro Bundle
    • Memberships for WooCommerce
    • WordPass
  • Store
    • Cart
    • Checkout
  • Blog
    • Basics [Free]
    • Tips and Tricks
    • Filters
    • Actions
    • Code Snippets
    • Shortcodes
    • Design
    • Release Announcements
  • Contact
  • Sign In
  • Show Search
Hide Search
Home » Tips and Tricks » Log in with Email or Username

Log in with Email or Username

Chad Butler · Jan 6, 2015 ·

This article is provided free. Find out how you can get full access to premium content, including how-to articles and support forums, as well as priority email support and member exclusive plugin extensions..

 

Here is a simple method for allowing users to log in with either their username or their email address.

This process allows the user to log in using either their username or their email address.  It’s not difficult to implement and leaves you with a clean process where you don’t have to worry about what to do when users change their email address.

The Process

The WP-Members login function uses the WP function wp_signon. This process filters the user authentication that happens as part of wp_signon just before it has a user to validate. It returns the user info to the wp_signon function to complete authentication.

So, we can use the WP filter hook “authenticate” to get the user’s account information with the WP function get_user_by.  get_user_by allows us to get the user’s username for authentication if we have another piece of information to match up the account.  We use get_user_by to first check by username to see if the user has input a valid username.  If that returns null, then we check by email.  That will provide us with a potential user account, and if not, then it returns a login error.

Next we need to make sure that the provided password matches the password for the user account.  We can do that with the wp_check_password function.  This function takes the provided (plain text) password and compares it with the stored (hashed) password for validation.  If the hash validates, then we can return the user for login.  Otherwise, we return a null value which will in turn cause the login to fail.

Adding the following to your functions.php file will handle the process:

add_filter( 'authenticate', 'my_login_with_email', 10, 3 );
function my_login_with_email( $user=null, $username, $password ){

	// First, check by username.
	$user = get_user_by( 'login', $username );

	// If the username is invalid, check by email.
	if( ! $user ) {
		$user = get_user_by( 'email', $username );	
	}
	
	// Validate the password.
	if( $user ) {
		if( wp_check_password( $password, $user->user_pass ) ) {
			// If password checks out, return a valid login.
			return $user;
		}
	}
	
	// Return a failed login.
	return new WP_Error( 'login', "Login Failed" );
}

Provide a Clean User Experience

Of course if you do this, you will want to let the user know they can use their username OR their email address to log in. To do that, you need to filter the login form to provide an appropriate label for the form.  Put plainly, we will change the label for “Username” to “Email or Username”.

The wpmem_inc_login_inputs filter allows us to do this very easily for the main body login form.  This filter has a number of array elements for the form components, so we just need to change the first field (array location “0”) value for “name” (the field label).  We can do that with the following filter:

add_filter( 'wpmem_inc_login_inputs', 'my_login_with_email_form' );
function my_login_with_email_form( $array ){
	$array[0]['name'] = 'Email or Username';
	return $array;
}

The sidebar widget does not have this kind of option (YET!).  So to change the sidebar label, we need to use the wpmem_sidebar_form filter to apply the PHP str_replace function to replace “Username” with “Email or Username” (or whatever you want it to read).  However, there are two caveats here.

First, we don’t want to accidentally change any of the HTML code other than the displayed label.  That could break the form.  str_replace acts as a search/replace all kind of function.  As a result, since there are other instances of “username” in the form’s HTML that we want untouched, I have chosen a more unique and specific string – “>Username<“.  Note the “>” and “<“.  These are the end of the opening label tag and the beginning of the closing label tag.  That way we make sure to change only the part we want. (The whole tag looks like this: >label for=”username”<Username>/label<)

The other important caveat is that if you are running a translated site in another language, “>Username<” will be “>whatever-username-translates-to<“.

Also, notice that we need to make sure our replacement string (the second string given to the str_replace function) also puts in the correct “>” and “<” or your HTML tags won’t be right.

add_filter( 'wpmem_sidebar_form', 'my_login_with_email_sidebar' );
function my_login_with_email_sidebar( $string ){
	return str_replace( '>Username<', '>Email or Username<', $string );
}

If you want to remove the “forgot username” link from the from the password reset form, you can do so with the wpmem_username_link_str filter using WP’s __return_empty_string to empty it:

add_filter( 'wpmem_username_link_str', '__return_empty_string' );

 

Other Considerations

This process would still require the user to create a (valid) username during the registration process. They just don’t need to remember it for logging in.

If you use this, you may also want to consider setting up the password reset to be reset with email only.

 

 

 

 

Tips and Tricks authenticate, filters, get_user_by, str_replace, wpmem_inc_login_inputs, wpmem_sidebar_form, wp_signon

Welcome to RocketGeek Interactive › Forums › Log in with Email or Username

Tagged: authenticate, filters, get_user_by, str_replace, wpmem_inc_login_inputs, wpmem_sidebar_form, wp_signon

  • This topic has 14 replies, 4 voices, and was last updated 6 years, 1 month ago by Chad Butler.
Viewing 7 reply threads
  • Author
    Posts
    • December 7, 2014 at 4:23 pm #6724
      Chad Butler
      Keymaster

      Here is a simple method for allowing users to log in with either their username or their email address. There is, of course, the Email as Username ext
      [See the full post at: Log in with Email or Username]

    • December 7, 2014 at 4:23 pm #6549
      peggymcelgunn@comcast.net
      Participant

      This code snippet worked for me. Exactly what I wanted — just to add the option for users to log-in with their email addresses. Thanks!

    • December 7, 2014 at 6:10 pm #6550
      Chad Butler
      Keymaster

      Glad to hear that!

    • January 5, 2015 at 7:04 am #6685
      tom
      Participant

      I have the same issue as “inetinitiatives” and was wondering if there is a “fix”
      “when I try to ‘activate’ the user in the admin view (using another of your extensions) I receive the “Your Nickname must be different than your login name. Please choose a different Nickname” error. The nickname field is pre-populated with the email address since it is now the user name”

      I cant find anything on the site that could be causing this, and don’t want to have to add a “nickname” field.

      I have the latest version of WP members and WP.
      Thanks

      • January 5, 2015 at 10:45 am #6686
        Chad Butler
        Keymaster

        Do you have iThemes Security installed? This message is part of that plugin and occurs when you have “Force users to choose a unique nickname” setting enabled (this is under Security > Settings and is way down at the bottom). So it actually has nothing to do with the Email as Username extension – this would effect anyone using iThemes Security with WP-Members with no nickname field during registration and moderated registration enabled (because you would be unable to update the user profile for activation unless a different nickname was provided).

        If you use that setting, then you are in a position where you either need to include a nickname field in your registration, or come up with some kind of default nickname that is not the username (email) at registration.

        If there is no nickname field, then the registration process defaults this to the username value (much like WordPress). So if the registration form does not have a “nickname” field, a default other than the username could be set with the wpmem_register_data filter.

        This filter comes after registration form validation has occurred, but before any additional processes that are hooked to the wpmem_pre_register_data action. So you could create some other default at this point. You could do that from posted form data, or create a method of generating a default. Something as simple as:

        add_filter( 'wpmem_register_data', 'my_default_nickname' );
        function my_default_nickname( $fields ) {
        	$fields['nickname'] = $fields['first_name'] . " " . $fields['last_name'];
        	return $fields;
        }

        This would create a nickname out of the first and last name separated by a space. Or you could make it equal to some other field, or essentially anything you wanted (within reason).

    • January 6, 2015 at 2:15 pm #6718
      rayyan
      Participant

      That was simple! I searched for this quite a bit. I suggest this snippet is feature more prominently on the blog so those who need it can easily find it.

      I think a lot of people would prefer allowing the user to choose either username or email to login.

      Thanks Chad, great plugin. I like it very much.

    • January 6, 2015 at 2:28 pm #6721
      rayyan
      Participant

      There seems to be a bug in that code.

      It does allow one to login with the email although it accepts a wrong password and authenticates the user.

      • January 6, 2015 at 3:31 pm #6725
        Chad Butler
        Keymaster

        Thanks for pointing that out… looking at it a little more, I can see the problem. Essentially, in that version, the user’s email returns a valid user. What we need to do is take that valid user and then check the password. If the password matches then we can return the valid user, otherwise returning an empty value will throw the login error. So something like this should do it:

        [[code redacted for errors - see the snippet in this post for corrections]]

        Pretty similar, but with the extra password validation.

        • January 6, 2015 at 3:52 pm #6727
          rayyan
          Participant

          Thank you Chad, that works just fine.

          • January 7, 2015 at 8:41 am #6740
            Chad Butler
            Keymaster

            So after some testing and retesting, I think we’ve come up with a solid code snippet for logging in with email or username.

            add_filter( 'authenticate', 'my_login_with_email', 10, 3 );
            function my_login_with_email( $user=null, $username, $password ){
            
            	/** First, check by username */
            	$user = get_user_by( 'login', $username );
            
            	/** If the username is invalid, check by email */
            	if( ! $user ) {
            		$user = get_user_by( 'email', $username );	
            	}
            	
            	/** validate the pasword */
            	if( $user ) {
            		if( wp_check_password( $password, $user->user_pass ) ) {
            			/** if password checks out, return a valid login */
            			return $user;
            		}
            	}
            	
            	/** return a failed login */
            	return new WP_Error( 'login', "Login Failed" );
            }

            Here’s what’s going on:

            First, it checks the user by their username. If they’ve provided an email address, that’s not going to return a valid user, in which case it will check to see if the provided login returns a user when checking by email.

            If either for these steps returns a valid user, then we move on to validate the password. If the password validates, a successful login is returned.

            In any other case (no valid user returned, an invalid password, etc) a login error is returned.

            Try that out. I’ll update the new post I put up on this subject (I had taken it down yesterday until a valid version was worked out) and clean up the scattered forum posts on this subject.

    • January 17, 2015 at 1:31 pm #6865
      rayyan
      Participant

      Hi Chad,

      Many of our users cannot login with their username after they reset their passwords. Many don’t try their email as their login.

      It’s causing many issues for us as we have 500+ new students in our new term and this has become a major roadblock for us.

      Is there a way this be fully tested?

      Thanks

    • January 17, 2015 at 1:42 pm #6866
      rayyan
      Participant

      Just to be clear, most people who are having problems logging in are those who registered recently and have reset their passwords. Could it be just user error? I don’t know, not sure.

      • January 17, 2015 at 4:00 pm #6868
        Chad Butler
        Keymaster

        Could it be just user error?

        Most likely.

        BTW… this is drifting off topic (the Email as Username extension) so I’ll be moving this segment to its own thread in the support forum. There’s good info/discussion here so I don’t want to lose it, but it’s getting away from the topic this thread should be focused on.

        • January 17, 2015 at 4:03 pm #6871
          rayyan
          Participant

          Perhaps it is. I’ll keep testing on my end to make sure.

          Thanks for your help.

          • January 17, 2015 at 4:34 pm #6893
            Chad Butler
            Keymaster

            It might help to dial down the random password complexity. There’s a method for that described here.

  • Author
    Posts
Viewing 7 reply threads
  • You must be logged in to reply to this topic.
Log In

Ready to get started?

Join Today!

© 2021 · butlerblog.com · RocketGeek is built using WordPress, WP-Members, and the Genesis Framework

  • butlerblog.com
  • WP-Members Support Subscription
  • Terms of Service
  • Refund Policy