如果我们想得到wordpress的某个未登录的用户数据,可以使用wp_set_current_user函数来实现。它能在不知道用户密码的情况下将用户设置为选中用户,并返回该用户对象,我们可以从用户对象中取得所有用户信息。
复制
wp_set_current_user( int $id, string $name = '' )
通过ID或用户名改变当前对象
描述
将$id设置为NULL,并在不知道用户ID的情况下指定名称。一些WordPress功能基于当前用户,而不是基于已签名的用户。因此,它打开了对未登录的用户编辑和执行操作的能力。
参数
- $id
(int) (必须) 用户id - $name
(string) (可选) 用户名,默认为空
返回值
(WP_User) 选择的用户对象
源码
文件位于 wp-includes/pluggable.php,在线地址:https://developer.wordpress.org/reference/files/wp-includes/pluggable.php/
复制
function wp_set_current_user( $id, $name = '' ) {
global $current_user;
// If `$id` matches the current user, there is 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;
}实例
请注意,设置当前用户不会登录该用户。此示例将设置当前用户并将其登录。
复制
$user_id = 12345;
$user = get_user_by( 'id', $user_id );
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user->user_login, $user );
}注意!运行此函数后,将影响与当前(真实)用户相关的所有内容。您必须还原真正的用户:
复制
$original_user_id = get_current_user_id(); // For example the real user ID is 7 wp_set_current_user( 15 ); // get_current_user_id() now returns 15 // Do other stuff here... // ... // get_current_user_id() still returns 15 // Restore the original user. wp_set_current_user( $original_user_id ); // get_current_user_id() now returns 7





评论 (0)