How do I log wordpress users without password
The answer that i have posted inside the comments , you can use that in the following way.
What you need to make this possible is. Create ajax hooks
for wordpress function which we are going to use for user login only with username, and , jQuery ajax call to that function.
First step to do here is go to : wp-content/themes/your_theme_name/
And open the file named functions.php
, then at the end of the file add the following code.
function username_login(){// Automatic login //$username = $_POST['username'];$user = get_user_by('login', $username ); // Redirect URL // if ( !is_wp_error( $user ) ) { wp_clear_auth_cookie(); wp_set_current_user ( $user->ID ); wp_set_auth_cookie ( $user->ID ); $redirect_to = user_admin_url(); echo json_encode(array('error_code'=>0)); exit(); } else { echo json_encode(array('error_code'=>1)); exit(); } exit();}add_action('wp_ajax_username_login','username_login');add_action('wp_ajax_nopriv_username_login','username_login');
As you can see , we have used a add_action
function to hook to our username_login
function from the ajax controller , read more about wordpress hooks here
The next step we need here is to make a ajax call to the function that we have created and make user login and then refresh the site when user is logged in. What you need is use the following code to send the request to Wordpress for login the user. Add the below code to your footer.php file, which is located inside wp-content/themes/your_theme_name/
and open footer.php
:
jQuery('#username_login').on('submit',function(e){ e.preventDefault(); var data = $(this).serializeArray(); data.push({ name:'action',value:'username_login' }); $.ajax({ url:"<?php echo admin_url('admin-ajax.php'); ?>";, type: 'POST', dataType: 'json', data:data, success:function(response){ if(response.error_code == 1){ alert('user cannot login') } else { alert('user logged in'); location.reload(); } } });});
As you can see in the above javascript code , we have form selector called username_login
, what we need to do now is create a form element with the id username_login
and inside it we need to create a input called username
with button type submit
:
<form id="username_login"> <input type="text" name="username" placeholder="Your username..." required/> <button type="submit" name="submit">Login</button></form>
Now that you have all , how this is going to work with this flow? . Well , when the user enters the username and hits the Login , an ajax request will be sent to the url : yoursite.com/wp-admin/admin-ajax.php?action=username_login
, with the parameter called action
and when the user logs in the site will be refreshed as the user is logged in and then user will have access to the normal user's features without any problem.