Example #1
0
 /**
  * Switches the current logged in user to the specified user.
  *
  * @param  int  $user_id      The ID of the user to switch to.
  * @param  bool $remember     Optional. Whether to 'remember' the user in the form of a persistent browser cookie. Default false.
  * @param  bool $set_old_user Optional. Whether to set the old user cookie. Default true.
  * @return bool|WP_User WP_User object on success, false on failure.
  */
 function switch_to_user($user_id, $remember = false, $set_old_user = true)
 {
     if (!($user = get_userdata($user_id))) {
         return false;
     }
     $old_user_id = is_user_logged_in() ? get_current_user_id() : false;
     if ($set_old_user && $old_user_id) {
         user_switching_set_olduser_cookie($old_user_id);
     } else {
         user_switching_clear_olduser_cookie(false);
     }
     wp_clear_auth_cookie();
     wp_set_auth_cookie($user_id, $remember);
     wp_set_current_user($user_id);
     if ($set_old_user) {
         /**
          * Fires when a user switches to another user account.
          *
          * @since 0.6.0
          *
          * @param int $user_id     The ID of the user being switched to.
          * @param int $old_user_id The ID of the user being switched from.
          */
         do_action('switch_to_user', $user_id, $old_user_id);
     } else {
         /**
          * Fires when a user switches back to their originating account.
          *
          * @since 0.6.0
          *
          * @param int       $user_id     The ID of the user being switched back to.
          * @param int|false $old_user_id The ID of the user being switched from, or false if the user is switching back
          *                               after having been switched off.
          */
         do_action('switch_back_user', $user_id, $old_user_id);
     }
     return $user;
 }
 /**
  * Switches the current logged in user to the specified user.
  *
  * @param  int  $user_id      The ID of the user to switch to.
  * @param  bool $remember     Whether to 'remember' the user in the form of a persistent browser cookie. Optional.
  * @param  bool $set_old_user Whether to set the old user cookie. Optional.
  * @return bool|WP_User WP_User object on success, false on failure.
  */
 function switch_to_user($user_id, $remember = false, $set_old_user = true)
 {
     if (!($user = get_userdata($user_id))) {
         return false;
     }
     $old_user_id = get_current_user_id();
     if ($set_old_user && $old_user_id) {
         user_switching_set_olduser_cookie($old_user_id);
     } else {
         user_switching_clear_olduser_cookie(false);
     }
     wp_clear_auth_cookie();
     wp_set_auth_cookie($user_id, $remember);
     wp_set_current_user($user_id);
     if ($set_old_user) {
         do_action('switch_to_user', $user_id, $old_user_id);
     } else {
         do_action('switch_back_user', $user_id, $old_user_id);
     }
     return $user;
 }