我正在将wordpress站点迁移到另一个站点。来自旧站点的用户需要使用新站点。我正在执行一个交错的实现,所以不想一次将所有用户都带来。
基本上,当用户尝试登录时,在登录验证之前,如果新站点上不存在该用户,我将使用api调用从旧站点获取用户详细信息,并在新站点上创建用户。
我正在使用wp\\u authenticate操作在对用户进行身份验证之前进行检查。这样就可以创建用户,然后进行身份验证。但身份验证失败。如果我再次尝试登录,它会正常工作,因此我知道凭据正常,所有数据都已正确写入。
感觉就像在服务器上的同一次旅行中,我无法创建用户和登录。
add_action( \'wp_authenticate\' , [$this,"preAuthenticate"],10,1);
public function preAuthenticate($username) {
try {
if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
throw new \\Exception("Not an email address - carry on");
}
$usr = get_user_by("email", $username);
if ($usr) {
throw new \\Exception("Already a user - carry on");
}
$this->getExternalUser($username);
} catch (\\Exception $ex) {
// no need to do anything
}
}
private function getExternalUser($emailAddress) {
try {
$oldUser = $this->readExternalUser($emailAddress);
if (!$oldUser)) {
throw new \\Exception("No user found");
}
$userData = [
\'user_pass\' => $this->randomPassword(), //This will be updated after the user has been created using the hash passed
\'user_login\' => $oldUser->login,
\'user_nicename\' => $oldUser->niceName,
\'user_email\' => $emailAddress,
\'role\' => "subscriber"
];
$result = wp_insert_user($userData);
$usr = get_user_by("ID", $result);
if (!$usr) {
throw new \\Exception("user not created");
}
global $wpdb;
$wpdb->update($wpdb->users, ["user_pass" => $oldUser->hash],[\'ID\' => $usr->ID]);
return true;
} catch (\\Exception $ex) {
return false;
}
}