Users & Login PHP Intermediate

Log Users Out of Other Devices When They Log In

Allow one active login per account. Logging in on a new device ends the sessions on every other device.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 6 lines
add_action( 'set_logged_in_cookie', function ( string $cookie, int $expire, int $expiration, int $user_id, string $scheme, string $token ): void {
	if ( '' === $token ) {
		return;
	}
	WP_Session_Tokens::get_instance( $user_id )->destroy_others( $token );
}, 10, 6 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

On paid membership sites, one account is sometimes shared by several people. Allowing only one session at a time stops that. It’s also a simple security measure: a new login always ends any older session someone else may have.

How it works

WordPress gives every login a session token, stored with the user. When the login cookie is set, the set_logged_in_cookie action receives the new token. destroy_others() then removes every other token for that user, so other browsers are logged out on their next page load.

Things to watch

  • Users who log in on their phone will be logged out on their laptop. Tell members before turning this on.
  • Administrators are included. To skip them, return early when user_can( $user_id, 'manage_options' ).

How to test it

Log in on one browser, then log in as the same user in a private window. Reload the first browser: you should be logged out.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only