函数文档

wp_set_current_user()

💡 云策文档标注

概述

wp_set_current_user() 函数用于通过用户 ID 或用户名设置当前用户,适用于需要临时切换用户身份的场景,例如编辑未登录用户或执行特定操作。它基于 WordPress 的当前用户机制,而非登录状态。

关键要点

  • 函数接受两个参数:$id(用户 ID,可为 null)和 $name(用户名),当 $id 未知时可设为 null 并指定 $name。
  • 设置当前用户不会自动登录用户,需结合 wp_set_auth_cookie() 和 wp_login 钩子实现登录。
  • 函数会触发 set_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 );
}

注意事项

  • 设置当前用户后,所有基于当前用户的功能(如权限检查)将受影响,需谨慎处理并适时恢复原始用户。
  • 函数不处理用户认证,仅改变当前用户对象,登录需额外步骤。

📄 原文内容

Changes the current user by ID or name.

Description

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.

Parameters

$idint|nullrequired
User ID.
$namestringrequired
User’s username.

Return

WP_User Current user User object.

More Information

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

Source

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

Hooks

do_action( ‘set_current_user’ )

Fires after the current user is set.

Changelog

Version Description
2.0.3 Introduced.

User Contributed Notes

  1. Skip to note 3 content

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

  2. Skip to note 4 content

    Attention!
    Running this function will affect everything related to the current(real) user, after it. You must restore the real 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