I’m trying to implement a custom registration process consisted of 4 steps.
At the first step user enters her credentials and pushes “continue” to proceed to the next step and the form is sent to the same page.
Here I successfully insert a new user to WP database and I want this user to be logged in right after this. I do it like this:
if ( isset($_POST["user-email"]) && isset($_POST["user-password"]) ) :
// Getting data from the Form
$user_login = esc_attr($_POST["user-email"]);
$user_password = esc_attr($_POST["user-password"]);
$user_email = esc_attr($_POST["user-email"]);
// Composing an array with user credentials data
$user_data =
array(
'user_login' => $user_login,
'user_pass' => $user_password,
'user_email' => $user_email,
'role' => 'student'
);
// Inserting new user to the db
wp_insert_user( $user_data );
// Trying to log in
$creds = array();
$creds['user_login'] = $user_login;
$creds['user_password'] = $user_password;
$creds['remember'] = true;
// As far as I know whis does the trick
$user = wp_signon( $creds, false );
if ( is_wp_error( $user ) ) echo $user->get_error_message();
endif;
The problem starts from here. wp_signon for some reason does not login user, which I check by the following:
if ( is_user_logged_in() ) : echo "Yuppiee!";
else : echo "FAIL!";
And I get “FAIL” all the time. Then I dug up the Internets and tried the following:
wp_set_current_user( $user->ID );
if ( is_user_logged_in() ) : echo "Yuppiee!";
else : echo "FAIL!";
And I have my “Yuppiee!” finally, but not for long. After page is reloaded I FAIL! again.
At the end I’ve got a new user added in my WP database and I can see her in the wp-admin/users panel and I can login this user through default wp-login form and I’ve got Yuppiee! all the way. But when I try to login the same user programmatically I got FAIL on page reload.
Can you help me to get through this? Please?!
I think this may be a WordPress bug. According to the documentation,
wp_signon()
is the correct function to log a user in.In your script, you are using
is_user_logged_in()
to verify the user was correctly logged in after your call towp_signon()
. is_user_logged_in() uses theglobal $current_user
variable which doesn’t appear to get set when usingwp_signon()
.wp_set_current_user()
sets theglobal $current_user
, but does not create the auth cookie needed to keep the user logged in.Try the following:
This way, you are logging the user in (creating the auth cookie) and setting the current user before attempting to verify using
is_user_logged_in()
.