WordPress custom login form without password
If you want to create a login process in WordPress without any password, this tutorial will be helpful for you. In this tutorial I will show you how to login into WordPress with username or email only. Let’s get started!
Step 1. You need a front-end user login form. Please copy the below code and then paste where you want to show the form.
// Form
<form autocomplete="off" method="post">
<div class="form-group">
<input id="userlog" name="userlog" type="text" placeholder="<?php echo esc_attr__('Username/email', 'theme-domain'); ?>" class="form-control" required="required">
</div>
<input type="hidden" name="action" value="my_login_action" />
<button type="submit"><?php echo esc_html__('Login', 'theme-domain'); ?></button>
</form>
Step 2. Then paste the below code in your theme’s functions.php file or your site-specific plugin.
// Calling ob_start function
function theme_domain_output_buffer() {
ob_start();
}
add_action('init', 'theme_domain_output_buffer');
// Login
add_action('init', function(){
// Return if not the login request
if( !isset( $_POST['action'] ) || $_POST['action'] !== 'my_login_action' )
return;
$result;
$username = $_POST['userlog'];
if ( ! $result ) {
$result = get_user_by( 'email', $username ); // user email
}
if ( ! $result ) {
$result = get_user_by('login', $username ); // user name
}
if ( !is_wp_error($result) ){
wp_clear_auth_cookie();
wp_set_current_user($result->ID);
wp_set_auth_cookie($result->ID);
wp_redirect( home_url( '/' ) );
exit;
}
die();
});
That’s it!
Happy coding. Thanks!