0
votes

I am trying to log in a wordpress user on my test site only by the user ID.

My goal is to send out an email to remind them to review a product they recently purchased, and via the email link I want to auto log them in and take them to the review form.

Then when the review is submitted, it's marked off as a 'verified buyer'

I made this user class and login test script to see if I could get it to work following the other documentation I found...

class UserAPI {
private $_id = 0;
private $_wpUser;

public function __construct(int $userID) {
    $this->_id = $userID;
    $this->_wpUser = get_user_by('id', $this->_id);
}


/*
 *  Log the user in
 */
public function login() {
    wp_clear_auth_cookie();

    wp_set_current_user( $this->_id, $this->_wpUser->user_login );
    wp_set_auth_cookie( $this->_id, true );
    do_action( 'wp_login', $this->_wpUser->user_login, $this->_wpUser );

    $currentUser = wp_get_current_user();

    if ( is_user_logged_in() ){
        echo 'logged in: ' . $currentUser->user_login;
    }

    else { echo 'not logged in'; }
}
}   


// Login test 
require('../../includes/userAPI.php');
require('../../../../../wp-load.php');

$userID = 1118; // random user in DB
$userAPI = new \mynamespace\UserAPI($userID);

// Log in user
$userAPI->login();

The output from login() shows the current user is the person I chose as a test from the existing db.

However if I load the wordpress site after I have done this - the user is NOT logged in.

I even confirmed with this...

add_action('init', function() {
$currentUser = wp_get_current_user();

    if ( is_user_logged_in() ){
        echo 'logged in: ' . $currentUser->user_login;
    }

    else { echo 'not logged in'; }

});

When I load the site, the test code shows "not logged in"

So I have the login by id test script open in one browser, and the wordpress home page in the other tab.

How can I fix this so that when I run the login script, then go to the wordpress home page tab and refresh it - the login is remember and the site loads with the user logged in?

Thank you

1

1 Answers

0
votes

The problem was a url missmatch when working with xampp locally

sometimes the browser or xampp would change my explict call to

http://127.0.0.1/devsite/

to...

http://localhost/devsite/

I imagine that was screwing up login cookies.