wp_set_current_user() WordPress Function

The wp_set_current_user() function sets the current user by ID. This function is called when a user logs in. It can also be used to change the current user during a script execution.

wp_set_current_user( int|null $id, string $name = '' ) #

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.


Top ↑

Parameters

$id

(int|null)(Required)User ID.

$name

(string)(Optional)User's username.

Default value: ''


Top ↑

Return

(WP_User) Current user User object.


Top ↑

More Information

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


Top ↑

Source

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


Top ↑

Changelog

Changelog
VersionDescription
2.0.3Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by the Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More