wp_get_session_token()WP 4.0.0

Retrieves the current session token from the logged_in cookie.

No Hooks.

Return

String. Token.

Usage

wp_get_session_token();

Examples

0

#1 Demo of what the function outputs

var_dump( wp_get_session_token() );
// string(43) "6nhBEF74hfMqVO1p0sdlJQ78Ui5yq85EZO8JIj31"
0

#2 Example: Session Uniqueness Check

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_get_session_token() code WP 6.7.2

function wp_get_session_token() {
	$cookie = wp_parse_auth_cookie( '', 'logged_in' );
	return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
}