One session per user in WordPress

In the recent 4.1 update WordPress introduced session management classes/functions/hooks.You can locate the “Logout of all other sessions” button your user profile in WP admin panel, click this button and you’ll be logged out of all other sessions. Other sessions would mean that you logged in from another computer, mobile phone/app etc.

This is an important update not only in terms of security and privacy but it also adds considerable options to expand the native CMS functionality, as WordPress now tracks sessions of logged in users, collecting information.

In this post we’ll add few lines of code to enable single logged in session per user in a WordPress site. Simply add this code in your theme functions.php file :

add_filter( 'authenticate','one_session_per_user', 30, 3 );

function one_session_per_user( $user, $username, $password ) {
$sessions = WP_Session_Tokens::get_instance( $user->ID );
$all_sessions = $sessions->get_all();
if ( count($all_sessions) ) {
$user = new WP_Error(‘already_signed_in’, __(‘<strong>ERROR</strong>: User already logged in.’));
}
return $user;
}

Try it and share your feedback !

7 comments

  1. Jo says:

    I tried adding this code to my themes function.php file and it broke the site. In Dreamweaver it says there is a syntax error on this line:

    $user = new WP_Error(‘already_signed_in’, __(‘ERROR: User already logged in.’));

    I’m afraid I don’t know any PHP to fix it!

    1. Mr.Vibe says:

      Check the single quotes. Many times when you copy code the quotes change. Copy the code in a text editor and re-type all the single/double quotes.

  2. Gumby says:

    is there a way to have the function code email the admin that this has happened?

  3. 收藏了好文乙未年(羊)三月初五 2015-4-23

  4. Dan says:

    do you think there is a way to edit this so that it does not do this with admin users?

  5. al3abenet says:

    it was a secure method to create a login user

  6. rajr11245 says:

    For some reasons this is not working!!! Appreciate your suggestions on this

Leave a Reply

%d bloggers like this: