Skip to content

Instantly share code, notes, and snippets.

@hellofromtonya
Created April 12, 2016 02:45
Show Gist options
  • Save hellofromtonya/c930de5d518c6cca6b0591f2d4b663f7 to your computer and use it in GitHub Desktop.
Save hellofromtonya/c930de5d518c6cca6b0591f2d4b663f7 to your computer and use it in GitHub Desktop.
Allow login via username or password for WordPress
<?php
namespace KnowTheCode;
add_filter( 'authenticate', __NAMESPACE__ . '\enable_login_with_email', 20, 3 );
/**
* Allow the user to log in via email address.
*
* If the `$email_or_username` parameter is not an email, then bail out, returning the `$user`.
* Otherwise, get the user's object via the email. Then reauthenticate their login
* via `wp_authenticate_username_password`.
*
* @since 1.0.0
*
* @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback
* @param string $email_or_username User's email or username from the login form.
* @param string $password User's password
*
* @return mixed
*/
function enable_login_with_email( $user, $email_or_username, $password ) {
if ( ! is_email( $email_or_username ) ) {
return $user;
}
$user = get_user_by( 'email', $email_or_username );
if ( is_wp_error( $user ) || ! $user instanceof \WP_User ) {
return $user;
}
return wp_authenticate_username_password( null, $user->user_login, $password );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment