wp_set_current_user( int $id, string $name = '' )

Changes the current user by ID or name.


Description 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 Parameters

$id

(int) (Required) User ID

$name

(string) (Optional) User's username

Default value: ''


Top ↑

Return Return

(WP_User) Current user User object


Top ↑

Source Source

File: wp-includes/pluggable.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;
}

Top ↑

Changelog Changelog

Changelog
Version Description
2.0.3 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note content
    Contributed by Codex

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

You must log in before being able to contribute a note or feedback.