0
votes

I programmatically log in a user in Wordpress (before headers are sent), using a session variable from a previous page. Later in this same page, in the body section, I var_dump: wp_get_current_user(). This returns the WP_User I logged in with. In the 'log in' section I have tried combinations of wp_signon(), wp_set_current_user() and wp_set_auth_cookie().

The problem comes, when I navigate away from this page, the user isn't logged in anymore. When I use wp-login.php, the user stays logged in. I've struggled with this for quite a while and can't seem to find, why the user won't stay logged in.

Can someone help please. I'll add snippets of currently used code below:

$creds = array(
"user_login" => $_SESSION['email'],
"user_password" => $newPass,
"remember" => true
);

$user = wp_signon( $creds );
if ( is_a( $user, 'WP_User' ) ) {
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID, true );
}

// Code follows ...


<body>
<?php if ( is_user_logged_in() ) var_dump(wp_get_current_user()); ?>
2

2 Answers

0
votes

Where is it being executed? You'll need to put it in an action. Use: add_action('theme_setup','your_code'); function your_code(){ //signin code block goes here };

0
votes

I eventually moved a segment of the code to another file. Something I failed to include was that I used wp_create_user on the same page. As soon as I replaced wp_set_current_user and wp_set_auth_cookie with wp_signon and moved it to a separate page, everything worked perfectly.