Autologin user after registration Wordpress

Mario picture Mario · Apr 24, 2013 · Viewed 9k times · Source

I am trying to autologin a user after registration.

I am trying this (functions.php):

    add_action( 'user_register', 'auto_login_user' );
    function auto_login_user($user_id) {
      $user = new WP_User($user_id);
      $user_login_var = $user->user_login;
      $user_email_var = stripslashes($user->user_email);
      $user_pass_var    = $user->user_pass;
      $creds = array();
      $creds['user_login'] = $user_login_var;
      $creds['user_password'] = $user_pass_var;
      $creds['remember'] = true;
      $user = wp_signon( $creds, false );
      if ( is_wp_error($user) )
        echo $user->get_error_message();

}

I am getting ERROR: The password you entered for the username "TheNewUserCreated" is incorrect. Lost your password?

How Can I take the password from the User object?

Also because this is a custom registration process in template registration.php I tried to take it with $_POST and run the function in that file but I didnt have any success that way too...

EDIT: Ok I am getting the encrypted password, so what is the solution here, how can I autologin the user? Maybe I can do this in registration.php page?

Answer

Pallavi Verma picture Pallavi Verma · May 9, 2014

Add below function to functions.php file

 function auto_login_new_user( $user_id ) {
        wp_set_current_user($user_id);
        wp_set_auth_cookie($user_id);
            // You can change home_url() to the specific URL,such as 
        //wp_redirect( 'http://www.wpcoke.com' );
        wp_redirect( home_url() );
        exit;
    }
 add_action( 'user_register', 'auto_login_new_user' );