wp_set_current_user

Changes the current user by ID or name.

Description

(WP_User) wp_set_current_user( (int) $id, (string) $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.

Returns (WP_User)

Current user User object

Parameters (2)

0. $id (int)
The id.
1. $name — Optional. (string) => ''
User's username

Usage

  1. if ( !function_exists( 'wp_set_current_user' ) ) { 
  2. require_once ABSPATH . WPINC . '/pluggable.php'; 
  3.  
  4. // The id. 
  5. $id = -1; 
  6.  
  7. // User's username 
  8. $name = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = wp_set_current_user($id, $name); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/pluggable.php  
  1. function wp_set_current_user($id, $name = '') { 
  2. global $current_user; 
  3.  
  4. // If `$id` matches the user who's already current, there's nothing to do. 
  5. if ( isset( $current_user ) 
  6. && ( $current_user instanceof WP_User
  7. && ( $id == $current_user->ID ) 
  8. && ( null !== $id ) 
  9. ) { 
  10. return $current_user; 
  11.  
  12. $current_user = new WP_User( $id, $name ); 
  13.  
  14. setup_userdata( $current_user->ID ); 
  15.  
  16. /** 
  17. * Fires after the current user is set. 
  18. * @since 2.0.1 
  19. */ 
  20.  
  21. return $current_user;