wp_set_current_user()设置当前登录为指定的用户

目录

描述

译文

插件可替代该函数的功能。若插件未重新定义函数,则使用该函数。
改变当前用户的编号或名称。

在用户编号未知的情况下可以将$id设为0并指定一个名称。

WordPress中一些功能基于当前用户而非登录用户。通过wp_set_current_user()可以对非登录用户进行编辑或执行动作。

原文

This function can be replaced via plugins. If plugins do not redefine these functions, then this will be used instead.

Changes the current user by ID or name.

Set $id to null and specify a name if you do not know a user's ID.

Some WordPress functionality is based on the current user and not based on the signed in user. wp_set_current_user() opens the ability to edit and perform actions on users who aren't signed in.

wp_set_current_user() 描述

用法

<?php wp_set_current_user$id$name ); ?>

wp_set_current_user() 用法

参数

$id

(integer) (必填) User ID

默认值: None

$name

(string) (可选) User's username

默认值: ''

Return Values

WP_User (object

WP_User object with the current user.

wp_set_current_user() 参数

示例

Note that setting the current user does not log in that user. This example will set the current user and log them in.

$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 );
}

wp_set_current_user() 示例

注意

  • This function can be replaced via plugins. If plugins do not redefine these functions, then this will be used instead.
  • 使用到: WP_User object
  • 使用到: setup_userdata()
  • 使用到: do_action() 调用 'set_current_user' hook after setting the current user.

wp_set_current_user() 注意

历史

添加于 版本: 2.0.4

wp_set_current_user() 历史

源文件

wp_set_current_user() 函数的代码位于 wp-includes/pluggable.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Changes the current user by ID or name.
 *
 * Set $id to null and specify a name if you do not know a user's ID.
 *
 * Some WordPress functionality is based on the current user and not based on
 * the signed in user. Therefore, it opens the ability to edit and perform
 * actions on users who aren't signed in.
 *
 * @since 2.0.3
 * @global WP_User $current_user The current user object which holds the user data.
 *
 * @param int    $id   User ID
 * @param string $name User's username
 * @return WP_User Current user User object
 */
function wp_set_current_user($id, $name = '') {
	global $current_user;

	if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->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;
}
endif;

if ( !function_exists('wp_get_current_user') ) :

wp_set_current_user() 源文件

相关