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()); ?>