我找到了另一个解决方案here 这使用了更好的方法(至少在我看来……)。无需设置任何cookie,它使用Wordpress API:
/**
* Programmatically logs a user in
*
* @param string $username
* @return bool True if the login was successful; false if it wasn\'t
*/
function programmatic_login( $username ) {
if ( is_user_logged_in() ) {
wp_logout();
}
add_filter( \'authenticate\', \'allow_programmatic_login\', 10, 3 ); // hook in earlier than other callbacks to short-circuit them
$user = wp_signon( array( \'user_login\' => $username ) );
remove_filter( \'authenticate\', \'allow_programmatic_login\', 10, 3 );
if ( is_a( $user, \'WP_User\' ) ) {
wp_set_current_user( $user->ID, $user->user_login );
if ( is_user_logged_in() ) {
return true;
}
}
return false;
}
/**
* An \'authenticate\' filter callback that authenticates the user using only the username.
*
* To avoid potential security vulnerabilities, this should only be used in the context of a programmatic login,
* and unhooked immediately after it fires.
*
* @param WP_User $user
* @param string $username
* @param string $password
* @return bool|WP_User a WP_User object if the username matched an existing user, or false if it didn\'t
*/
function allow_programmatic_login( $user, $username, $password ) {
return get_user_by( \'login\', $username );
}
我认为代码是不言而喻的:
过滤器将搜索给定用户名的WP\\u用户对象并返回它。对函数的调用wp_set_current_user
返回的WP\\u用户对象wp_signon
, 功能检查is_user_logged_in
确保您已登录,仅此而已!
在我看来,这是一段漂亮而干净的代码!