Active Login Sessions Overview
Adds Users > Active Sessions, listing everyone who is currently logged in with their login time, IP address and browser, and lets you end a user's sessions with one click.
Opens WPIDE on
Code
add_action( 'admin_menu', function () {
add_users_page( 'Active Sessions', 'Active Sessions', 'edit_users', 'wpide-sessions', function () {
if ( isset( $_POST['wpide_end_user'] ) && check_admin_referer( 'wpide_end_sessions' ) && current_user_can( 'edit_users' ) ) {
$target = absint( $_POST['wpide_end_user'] );
if ( $target && $target !== get_current_user_id() && current_user_can( 'edit_user', $target ) ) {
WP_Session_Tokens::get_instance( $target )->destroy_all();
echo '<div class="notice notice-success"><p>Sessions ended.</p></div>';
}
}
$rows = array();
foreach ( get_users( array( 'meta_key' => 'session_tokens', 'number' => 200, 'fields' => array( 'ID', 'user_login' ) ) ) as $user ) {
foreach ( WP_Session_Tokens::get_instance( (int) $user->ID )->get_all() as $session ) {
$rows[] = array( $user, $session );
}
}
usort( $rows, function ( $a, $b ) {
return (int) $b[1]['login'] - (int) $a[1]['login'];
} );
echo '<div class="wrap"><h1>Active Sessions</h1><table class="widefat striped"><thead><tr><th>User</th><th>Logged in</th><th>Expires</th><th>IP address</th><th>Browser</th><th></th></tr></thead><tbody>';
if ( ! $rows ) {
echo '<tr><td colspan="6">No active sessions.</td></tr>';
}
foreach ( $rows as list( $user, $session ) ) {
echo '<tr><td>' . esc_html( $user->user_login ) . '</td>';
echo '<td>' . esc_html( human_time_diff( (int) $session['login'] ) . ' ago' ) . '</td>';
echo '<td>' . esc_html( wp_date( 'Y-m-d H:i', (int) $session['expiration'] ) ) . '</td>';
echo '<td>' . esc_html( isset( $session['ip'] ) ? $session['ip'] : '' ) . '</td>';
echo '<td>' . esc_html( isset( $session['ua'] ) ? wp_html_excerpt( $session['ua'], 60, '...' ) : '' ) . '</td><td>';
if ( (int) $user->ID !== get_current_user_id() ) {
echo '<form method="post">';
wp_nonce_field( 'wpide_end_sessions' );
echo '<button class="button" name="wpide_end_user" value="' . (int) $user->ID . '">End sessions</button></form>';
}
echo '</td></tr>';
}
echo '</tbody></table></div>';
} );
} );
Notes
Shows up to 200 users with active sessions, most recent logins first.
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.