首页 > 解决方案 > WordPress 登录用户仅使用用户 ID - 登录不记得问题

问题描述

我试图仅通过用户 ID 在我的测试站点上登录 wordpress 用户。

我的目标是发送一封电子邮件,提醒他们审查他们最近购买的产品,并通过电子邮件链接让他们自动登录并将他们带到审查表。

然后在提交评论时,将其标记为“已验证买家”

我制作了这个用户类和登录测试脚本,看看我是否可以按照我找到的其他文档让它工作......

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

login() 的输出显示当前用户是我从现有数据库中选择作为测试的人。

但是,如果我在完成此操作后加载 wordpress 网站 - 用户未登录。

我什至证实了这一点......

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'; }

});

当我加载网站时,测试代码显示“未登录”

因此,我在一个浏览器中打开了通过 id 登录测试脚本,并在另一个选项卡中打开了 wordpress 主页。

我该如何解决这个问题,以便在我运行登录脚本时,然后转到 wordpress 主页选项卡并刷新它 - 登录名被记住并且网站在用户登录时加载?

谢谢

标签: wordpress

解决方案


问题是在本地使用 xampp 时 url 不匹配

有时浏览器或 xampp 会将我的显式调用更改为

http://127.0.0.1/devsite/

至...

http://localhost/devsite/

我想那是搞砸了登录cookie。


推荐阅读