I am looking to programmatically login users from php
, but after reviewing multiple threads about achieving this I have found that none of the methods work for me and I am not sure why. Currently I am running the code from the functions.php
file of my theme:
function test_login() {
if (!isset($_GET['uname'])) return;
function login($user) {
do_action('wp_login', $user->data->user_login, $user);
wp_set_current_user( $user->ID, $user->data->user_login );
wp_set_auth_cookie( $user->ID, true );
header('hdrs: are_setting');
}
$creds = array();
$creds['user_login'] = $_GET['uname'];
$creds['user_password'] = 'password';
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ) {
// echo $user->get_error_message();
} else {
login($user);
wp_redirect( 'https://example.com/home' );
// exit;
}
}
add_action('after_setup_theme', 'test_login'); // Also tried init
I have also tried running this code in a separate file, but there is no difference. The code finds the user no problem, the login
function is executed and I can even see the hdrs
header in my browser. But after the redirect I am still logged out. I do suspect that caching may be involved in this, but I tried disabling all my caching plugins, but there may be something going on with the hosting provider or cloudflare. Either way, a "manual" login works without issue. I hope that I am missing something obvious here.