The issue arises because the is_user_logged_in() function relies on the authentication cookies being recognized by the WordPress request lifecycle. When you set the authentication cookies using wp_set_auth_cookie(), they are sent to the browser, but they are not yet available to the same request that initiated the cookie setting. The cookies will only be recognized on subsequent requests.
// Handle login link
add_action('parse_request', function (&$wp) {
if (array_key_exists('login_link', $wp->query_vars)) {
$user = // get user and validate hashed token from url...
// Log in the user
wp_clear_auth_cookie();
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID);
// Set the global $current_user manually for the current request
global $current_user;
$current_user = $user;
do_action('wp_login', $user->user_login, $user);
// Redirect to home
wp_safe_redirect(home_url());
exit();
}
});
1).global $current_user; $current_user = $user;: This ensures that the global $current_user variable is set for the current request.
2). wp_set_current_user($user->ID);: Even though you’ve already set the user in wp_set_auth_cookie(), this ensures that WordPress internally knows about the current user for this request.
By doing this, is_user_logged_in() will correctly recognize the logged-in status for the current request.