Skip to content
Advertisement

wp_signon not working, as moving to next page gives me no user logged in

In my wordpress project I am have created template page where user can register. Now Problem I am facing is making user logged in after registration. I have created a user and after that I have tried to make the user log in using below code.

$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );

I have also created a log in template to allow user loged in by using same above code but same issues occurs. Now problem I am facing is as soon as I moved to new page, I found user is not logged in.

I guess cookies are not getting saved. I have also tried using

wp_set_auth_cookie($user->ID,true);

But no success.

I cannot understand when we logged in using wp-admin then one can successfully logged in or if I am using wp_login_form() then that also works fine. Then wats is the problem by using above code.

Please help as I have to anyhow make user logged in after registration.

Advertisement

Answer

Your code is correct. Both pieces of code will authenticate and login the user succesfully.

However you are missing the redirect. After calling wp_signon() or wp_set_auth_cookie(), you should redirect the user to make sure the new cookie is being loaded.

This can be done by using the following code right after your wp_signon() or wp_set_auth_cookie() call:

wp_redirect($_SERVER['REQUEST_URI']);
exit;

In case you want to redirect the user to a specific page, you can replace $_SERVER['REQUEST_URI'] with the URL where you want to redirect the user to.

A sidenote: you should make sure that this code is called before the headers are being sent, as wp_redirect() will not work after the headers are sent.

EDIT: In case the above does not work, you might try the entire login process ($user should be the user object, which you can get with the get_user_by() function):

do_action('wp_login', $user->user_login, $user);
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID );
$redirect_to = $_SERVER['REQUEST_URI'];
wp_safe_redirect($redirect_to);
exit;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement