bp_member_switch_to( int $user_id, bool $remember = false, bool $set_old_user = true )

Switches the current logged in user to the specified user.

Description

Parameters

$user_id

(Required) The ID of the user to switch to.

$remember

(Optional) Whether to 'remember' the user in the form of a persistent browser cookie.

Default value: false

$set_old_user

(Optional) Whether to set the old user cookie.

Default value: true

Return

(false|WP_User) WP_User object on success, false on failure.

Source

File: bp-members/bp-members-functions.php

function bp_member_switch_to( $user_id, $remember = false, $set_old_user = true ) {
	$user = get_userdata( $user_id );

	if ( ! $user ) {
		return false;
	}

	$old_user_id  = ( is_user_logged_in() ) ? get_current_user_id() : false;
	$old_token    = function_exists( 'wp_get_session_token' ) ? wp_get_session_token() : '';
	$auth_cookie  = bp_member_switching_get_auth_cookie();
	$cookie_parts = wp_parse_auth_cookie( end( $auth_cookie ) );

	if ( $set_old_user && $old_user_id ) {
		// Switching to another user
		$new_token = '';
		// We'll not override the old user
		if ( empty( $auth_cookie ) ) {
			bp_member_switching_set_olduser_cookie( $old_user_id, false, $old_token );
		}
	} else {
		// Switching back, either after being switched off or after being switched to another user
		$new_token = isset( $cookie_parts['token'] ) ? $cookie_parts['token'] : '';
		bp_member_switching_clear_olduser_cookie( false );
	}

	/**
	 * Attaches the original user ID and session token to the new session when a user switches to another user.
	 *
	 * @param array $session Array of extra data.
	 * @param int $user_id User ID.
	 *
	 * @return array Array of extra data.
	 */
	$session_filter = function ( array $session, $user_id ) use ( $old_user_id, $old_token ) {
		$session['switched_from_id']      = $old_user_id;
		$session['switched_from_session'] = $old_token;

		return $session;
	};

	add_filter( 'attach_session_information', $session_filter, 99, 2 );

	wp_clear_auth_cookie();
	wp_set_auth_cookie( $user_id, $remember, '', $new_token );
	wp_set_current_user( $user_id );

	if ( $old_token && $old_user_id && ! $set_old_user ) {
		// When switching back, destroy the session for the old user
		$manager = WP_Session_Tokens::get_instance( $old_user_id );
		$manager->destroy( $old_token );
	}

	return $user;
}

Changelog

Changelog
Version Description
BuddyBoss 1.0.0 Introduced.

Questions?

We're always happy to help with code or other questions you might have! Search our developer docs, contact support, or connect with our sales team.