0

I am trying to login the user using the email only (The password is checked with an API from another system). The thing is all my code is running except for the part of autologin, below is my function:

I already tried different functionalities available online but what is happening with the below code is:

1- it will let the user login, but after refresh or going to any page which requires the user to be logged it, wordpress logs the user out.

function auth_new_user($username){

if(!username_exists($username)) {
  // Generate the password and create the user

$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $username, $password, $username );
// Set the nickname
wp_update_user(
array(
  'ID'          =>    $user_id,
  'nickname'    =>    $username
  )
 );
 // Set the role
 $user = new WP_User( $user_id );
 $user->set_role( 'Subscriber' );
 auto_login_usr($user_id,$username);
  } // end if
else{
 $the_user = get_user_by('email', $username);
 $user_id = $the_user->ID;
 echo $user_id;
 auto_login_usr($user_id,$username);
}

}

function auto_login_usr($user_id, $username) {

$user = get_user_by( 'id', $user_id ); 
echo $user->user_login;
echo $user->password;
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id ,false, is_ssl());
do_action( 'wp_login', $user->user_login );
}

}

After logging in, WordPress automatically logs the user out ( keeps the user logged in for a second ). Note i debugged the code more than once and everything is appearing correctly ( User Id, User_login, and username).

Appreciate your help.

devterm
  • 32
  • 7
  • Please checkout https://stackoverflow.com/questions/19949876/how-to-auto-login-after-registration-in-wordpress-with-core-php . I hope this will help you – Jogi Mehul Dec 31 '18 at 10:05
  • Thank you for your comment, the thing is i am doing the registration manually and my functions already inside functions.php ... note wp_login is depricated – devterm Dec 31 '18 at 10:50
  • Thank you i fixed it, below is the answer and the fix :) – devterm Dec 31 '18 at 12:07

1 Answers1

0

It is fine i fixed it myself, the headers was already sent. i should call the functions after_theme_setup:

  1. either with a hook
  2. Or Before calling get_header function
devterm
  • 32
  • 7