Halloween Sale 15% off Ends in See the plans
PHP

Active Sessions Column With "Log Out Everywhere"

Shows how many devices each user is logged in on, with a link to end all of that user's sessions from the Users screen.

Don’t have WPIDE yet? Install it on your site

Code

add_filter( 'manage_users_columns', function ( $columns ) {
    $columns['wpide_sessions'] = 'Sessions';

    return $columns;
} );

add_filter( 'manage_users_custom_column', function ( $output, $column, $user_id ) {
    if ( 'wpide_sessions' !== $column ) {
        return $output;
    }

    $count = count( WP_Session_Tokens::get_instance( $user_id )->get_all() );

    if ( ! $count ) {
        return '0';
    }

    $output = (string) $count;

    if ( current_user_can( 'edit_user', $user_id ) && get_current_user_id() !== (int) $user_id ) {
        $url     = wp_nonce_url( admin_url( 'admin-post.php?action=wpide_end_sessions&user_id=' . (int) $user_id ), 'wpide_end_sessions_' . (int) $user_id );
        $output .= '<br><a href="' . esc_url( $url ) . '">Log out everywhere</a>';
    }

    return $output;
}, 10, 3 );

add_action( 'admin_post_wpide_end_sessions', function () {
    $user_id = isset( $_GET['user_id'] ) ? absint( $_GET['user_id'] ) : 0;

    if ( ! $user_id || ! current_user_can( 'edit_user', $user_id ) ) {
        wp_die( 'You are not allowed to do this.' );
    }

    check_admin_referer( 'wpide_end_sessions_' . $user_id );
    WP_Session_Tokens::get_instance( $user_id )->destroy_all();

    wp_safe_redirect( add_query_arg( 'wpide_sessions_ended', 1, admin_url( 'users.php' ) ) );
    exit;
} );

add_action( 'admin_notices', function () {
    if ( isset( $_GET['wpide_sessions_ended'] ) ) {
        echo '<div class="notice notice-success is-dismissible"><p>The user was logged out on all devices.</p></div>';
    }
} );

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.