Is there a way to display a list of currently logged in users?
Ideally it would just show their name and gravatar.
Personaly I would use the session_tokens meta key to determine if a user is online (or has a running session) or not.
$aUsers = get_users([
'meta_key' => 'session_tokens',
'meta_compare' => 'EXISTS'
]);
You'll get a list of Users with running sessions. Then you can use that for your output.
echo sprintf(
'Users online: %s',
implode(', ', array_map(function($oUser){
return get_avatar( $oUser->ID, 96 ) . '<span class="username">'$oUser->display_name.'</span>';
}, $aUsers))
);
You could even display the session ip addresses if you modify the last bit of code.
echo sprintf(
'Users online: %s',
implode(', ', array_map(function($oUser){
$aCurrentSessions = get_user_meta($oUser->ID, 'session_tokens', true);
return get_avatar( $oUser->ID, 96 ) . '<span class="username">'$oUser->display_name.'</span> (' .
implode('; ', array_map(function($aSession) {
return $aSession['ip']; // only return the session ips
}, $aCurrentSessions)) . ')';
}, $aUsers))
);
Wordpress does not have a built in function for this, but you can easily add one yourself. For example, you can use the wp_login hook to store each users last login time. Then you can list the users that logged in within the last 30 minutes or so as online.
add_action('wp_login', 'store_last_login', 10, 2);
function store_last_login($current_user) {
global $current_user;
get_currentuserinfo();
$user = $current_user->user_login;
update_user_meta($current_user->ID, 'last_login', current_time('mysql', 1));
}
Then, you can echo out the users that logged in within the last twenty minutes ( or whatever timeframe you choose) with something like:
function list_online_users() {
$users = get_users( 'blog_id=1' );
foreach ($users as $online) {
$getLastLogin = (get_user_meta($online->ID, 'last_login', true));
$lastLogin = new DateTime($getLastLogin);
$since_start = $lastLogin->diff(new DateTime(current_time('mysql', 1)));
$minutesSinceLogin = $since_start->i;
// this will list every user and whether they logged in within the last 30 minutes
if ($minutesSinceLogin > 30 ) {
echo '<li>'.$online->user_login . ' is offline </li>';
} else {
echo '<li>'.$online->user_login . ' is online </li>';
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With