按ID或名称更改当前用户。
原型
wp_set_current_user( int $id, string $name = '' )
描述
如果你不知道用户的ID,请将$ id设置为null并指定名称。
参数
$id
(int)
(Required)
用户身份
$name
(string)
(Optional)
用户的用户名
返回值
(WP_User)
当前用户User对象
源文件
路径:wp-includes/pluggable.php
<?php
...
function wp_set_current_user($id, $name = '') {
global $current_user;
// If `$id` matches the user who's already current, there's nothing to do.
if ( isset( $current_user )
&& ( $current_user instanceof WP_User )
&& ( $id == $current_user->ID )
&& ( null !== $id )
) {
return $current_user;
}
$current_user = new WP_User( $id, $name );
setup_userdata( $current_user->ID );
/**
* Fires after the current user is set.
*
* @since 2.0.1
*/
do_action( 'set_current_user' );
return $current_user;
}
...
?>
其他
英文文档:https://developer.wordpress.org/reference/functions/wp_set_current_user/