How to Allow Both Username or Email to Login WordPress

In WordPress admin panel user can only login by using username. Now do you want to add extra functionality by adding email address as well to login? You can do this by installing one simple plugin WP Email Login which completely free. you can get this from WordPress plugin directory. But installing an extra plugin for only this functionality could slow down your site. Good news is you can avoid to install the plugin instead just add some code in your theme’s functions. Here is the code to allow both username or email to login wordpress.

login-with-email

[php]
function dr_email_login_authenticate( $user, $username, $password ) {
if ( is_a( $user, ‘WP_User’ ) )
return $user;

if ( !empty( $username ) ) {
$username = str_replace( ‘&’, ‘&’, stripslashes( $username ) );
$user = get_user_by( ’email’, $username );
if ( isset( $user, $user->user_login, $user->user_status ) && 0 == (int) $user->user_status )
$username = $user->user_login;
}

return wp_authenticate_username_password( null, $username, $password );
}
remove_filter( ‘authenticate’, ‘wp_authenticate_username_password’, 20, 3 );
add_filter( ‘authenticate’, ‘dr_email_login_authenticate’, 20, 3 );

if ( !function_exists( ‘is_super_admin’ ) ) :
function get_super_admins() {
global $super_admins;

if ( isset( $super_admins ) )
return $super_admins;
else
return get_site_option( ‘site_admins’, array( ‘admin’ ) );
}

function is_super_admin( $user_id = false ) {
if ( ! $user_id ) {
$current_user = wp_get_current_user();
$user_id = ! empty( $current_user ) ? $current_user->id : 0;
}

if ( ! $user_id )
return false;

$user = new WP_User( $user_id );

if ( is_multisite() ) {
$super_admins = get_super_admins();
if ( is_array( $super_admins ) && in_array( $user->user_login, $super_admins ) )
return true;
} else {
if ( $user->has_cap( ‘delete_users’ ) )
return true;
}

return false;
}
endif;

function username_or_email_login() {
if ( ‘wp-login.php’ != basename( $_SERVER[‘SCRIPT_NAME’] ) )
return;

?><script type="text/javascript">
if ( document.getElementById(‘loginform’) )
document.getElementById(‘loginform’).childNodes[1].childNodes[1].childNodes[0].nodeValue = ‘<?php echo esc_js( __( ‘Username / Email’, ’email-login’ ) ); ?>’;

if ( document.getElementById(‘login_error’) )
document.getElementById(‘login_error’).innerHTML = document.getElementById(‘login_error’).innerHTML.replace( ‘<?php echo esc_js( __( ‘username’ ) ); ?>’, ‘<?php echo esc_js( __( ‘Username / Email’ , ’email-login’ ) ); ?>’ );
</script><?php
}
add_action( ‘login_form’, ‘username_or_email_login’ );
[/php]

This is the login page before using the code:

login-with-email1

 

This is the login page after using the code:

login-with-email2

Get more tricky and effective query in WordPress Query category.

Author: mytutorialguru

Share This Post On

Submit a Comment

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