Action Since 1.4.0 The `$old_token` parameter was added. uncanny-learndash-toolkit

switch_off_user

Fires when a user switches off. Fires when a user's account is deactivated, passing their ID and session token.

add_action( 'switch_off_user', $callback, 10, 2 );

Description

Fires after a user switches back to their original account, making them the currently logged-in user again. It provides the ID and session token of the user who was previously switched off. Developers can use this hook to perform cleanup or specific actions related to the user returning to their original session.


Usage

add_action( 'switch_off_user', 'your_function_name', 10, 2 );

Parameters

$old_user_id (int)
The ID of the user switching off.
$old_token (string)
The token of the session of the user switching off.

Examples

// Example of adding an action to the 'switch_off_user' hook.
// This function will be executed when a user switches off from another user.
// It logs the user ID and session token to the WordPress debug log.
add_action( 'switch_off_user', 'my_custom_log_user_switch_off', 10, 2 );

/**
 * Logs the user ID and session token when a user switches off.
 *
 * @param int    $old_user_id The ID of the user switching off.
 * @param string $old_token   The token of the session of the user switching off.
 */
function my_custom_log_user_switch_off( $old_user_id, $old_token ) {
	// Ensure we have a user ID and token before logging.
	if ( ! empty( $old_user_id ) && ! empty( $old_token ) ) {
		// Use WordPress's error_log for more robust logging.
		error_log( sprintf( 'User switching off: User ID %d, Token: %s', $old_user_id, $old_token ) );

		// You could also perform other actions here, like updating a meta field
		// for the original user or sending a notification.
		// For example:
		// update_user_meta( $old_user_id, 'last_switch_off_time', current_time( 'mysql' ) );
	}
}

Placement

This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.


Source Code

src/includes/user-switching.php:1591

function switch_off_user() {
		$old_user_id = get_current_user_id();

		if ( ! $old_user_id ) {
			return false;
		}

		$old_token = function_exists( 'wp_get_session_token' ) ? wp_get_session_token() : '';

		user_switching_set_olduser_cookie( $old_user_id, false, $old_token );
		wp_clear_auth_cookie();
		wp_set_current_user( 0 );

		/**
		 * Fires when a user switches off.
		 *
		 * @since 0.6.0
		 * @since 1.4.0 The `$old_token` parameter was added.
		 *
		 * @param int    $old_user_id The ID of the user switching off.
		 * @param string $old_token   The token of the session of the user switching off.
		 */
		do_action( 'switch_off_user', $old_user_id, $old_token );

		return true;
	}

Scroll to Top