One session per user in WordPress

One session per user in WordPress/BuddyPress site.

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 !

June 22, 2016

7 responses on "One session per user in WordPress"

  1. 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!

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

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

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

  5. it was a secure method to create a login user

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

Leave a Reply

top
Template Design © VibeThemes. All rights reserved.
%d bloggers like this: