wp_destroy_other_sessions()WP 4.0.0

Deletes all active sessions except the current one from the database for the current user.

This may be useful for managing security when, for example, we want to prevent a user from logging in simultaneously from multiple devices.

No Hooks.

Returns

null. Nothing (null).

Usage

wp_destroy_other_sessions();

Examples

0

#1 Forced support for only one session

In this example, all active sessions for the current user are checked. If a session with a token different from the current one is found, all other sessions are terminated.

if ( is_user_logged_in() ) {
	$current_token = wp_get_session_token();
	$all_sessions = wp_get_all_sessions( get_current_user_id() );

	foreach ( $all_sessions as $token => $session_data ) {
		// If another session is found, terminate it
		if ( $token !== $current_token ) {
			wp_destroy_other_sessions();
			break;
		}
	}
}

Changelog

Since 4.0.0 Introduced.

wp_destroy_other_sessions() code WP 7.0

function wp_destroy_other_sessions() {
	$token = wp_get_session_token();
	if ( $token ) {
		$manager = WP_Session_Tokens::get_instance( get_current_user_id() );
		$manager->destroy_others( $token );
	}
}