Users Online Count in the Admin Bar
Shows administrators how many logged-in users were active in the last five minutes, with their names in a dropdown.
Opens WPIDE on
Code
// Minutes a user counts as online after their last page view.
$wpide_online_window = 5;
add_action( 'init', function () use ( $wpide_online_window ) {
$user_id = get_current_user_id();
if ( ! $user_id || wp_doing_cron() || wp_doing_ajax() ) {
return;
}
$online = get_transient( 'wpide_users_online' );
$online = is_array( $online ) ? $online : array();
$now = time();
if ( isset( $online[ $user_id ] ) && $now - $online[ $user_id ] < MINUTE_IN_SECONDS ) {
return; // Updated less than a minute ago.
}
$online[ $user_id ] = $now;
$online = array_filter( $online, function ( $time ) use ( $now, $wpide_online_window ) {
return $now - $time < $wpide_online_window * MINUTE_IN_SECONDS;
} );
set_transient( 'wpide_users_online', $online, HOUR_IN_SECONDS );
} );
add_action( 'admin_bar_menu', function ( $wp_admin_bar ) use ( $wpide_online_window ) {
if ( ! current_user_can( 'list_users' ) ) {
return;
}
$online = get_transient( 'wpide_users_online' );
$online = is_array( $online ) ? $online : array();
$now = time();
$online = array_filter( $online, function ( $time ) use ( $now, $wpide_online_window ) {
return $now - $time < $wpide_online_window * MINUTE_IN_SECONDS;
} );
$wp_admin_bar->add_node( array(
'id' => 'wpide-online',
'parent' => 'top-secondary',
'title' => sprintf( '%d online', count( $online ) ),
) );
foreach ( array_slice( array_keys( $online ), 0, 20 ) as $user_id ) {
$user = get_userdata( $user_id );
if ( $user ) {
$wp_admin_bar->add_node( array(
'id' => 'wpide-online-' . $user_id,
'parent' => 'wpide-online',
'title' => esc_html( $user->display_name ),
'href' => get_edit_user_link( $user_id ),
) );
}
}
}, 5 );
Notes
Writes one small transient at most once a minute per logged-in user.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.