When it comes to building web applications, I’m a fan of letting a user use their email as their primary login – in fact, I’d go as far as to say that I wish our emailĀ was our primary identity: They are unique, it’s a single thing to remember, and we all must have them in order to get online these days.

To that end, whenever I’m working on an application that requires a username and password, I always default to using the email address for the user’s identification. Everything else can be managed in a profile setting, right?

If you’re building an application in WordPress where you’re building custom registration mechanisms through your own views, validation, and so on, you may find yourself needing to check to see if a user already exists.

And if you – like me – often use email as the user name, there’s a really easy way to perform this check.

Have WordPress Check if a User Exists

Assuming that the email address is valid and is contained in the $_POST collection, you can do this:

// First, make sure the email address is set
if ( isset( $_POST['email-address'] ) && ! empty( $_POST['email-address'] ) ) {

  // Next, sanitize the data
  $email_addr = trim( strip_tags( stripslashes( $_POST['email-address'] ) ) );

  // Now use PHP to check if it's a valid email format
  if ( filter_var( $email_addr, FILTER_VALIDATE_EMAIL ) ) {

    if( false == get_user_by( 'email', $email_addr ) ) {
      // The user doesn't exist
    } else {
      // The user exists
    }

  } else {

    // An invalid email format has been entered

  }

}

Now, to be clear, this is simply demonstration code. I believe that there are cleaner ways to go about writing this type of functionality through the use of helper functions, fewer conditionals, and so on.

But this post isn’t really about the best way to architect this solution. Instead, it’s simply demonstrating a way that you can check to see if a WordPress user already exists by a specified email address and, in this case, that method is get_user_by.

What About Other Credentials?

get_user_by in The WordPress Codex

`get_user_by` in The WordPress Codex

Honestly, this function is flexible and is well documented in the WordPress Codex.

You can actually use a person’s email, the user ID, the slug, or their login name to check for their existence in the system.

Next time you’ve got to determine if a user already exists and you have at least one piece of information about the account that you’re trying to create, check out this function.