WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/wp set current user

Description

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.

Usage

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

Parameters

$id
(integer) (required) User ID
Default: None
$name
(string) (optional) User's username
Default: ''

Return Values

WP_User (object) 
WP_User object with the current user.

Examples

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

Notes

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

Change Log

Since: 2.0.4

Source File

wp_set_current_user() is located in wp-includes/pluggable.php.

Related

Current User Functions: get_current_user_id(), get_currentuserinfo(), wp_get_current_user(), wp_set_current_user(), current_user_can(), current_user_can_for_blog()

See also index of Function Reference and index of Template Tags.