Halloween Sale 15% off Ends in See the plans
PHP

"Log Out Other Devices" Button for Members

Adds a [wpide_logout_others] shortcode with a button that signs the member out of every other browser and device, keeping the current one logged in.

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

Code

add_action( 'template_redirect', function () {
    if ( empty( $_POST['wpide_logout_others_nonce'] ) || ! is_user_logged_in() ) {
        return;
    }

    if ( ! wp_verify_nonce( sanitize_key( $_POST['wpide_logout_others_nonce'] ), 'wpide_logout_others' ) ) {
        wp_die( 'The form expired. Please go back and try again.' );
    }

    WP_Session_Tokens::get_instance( get_current_user_id() )->destroy_others( wp_get_session_token() );

    wp_safe_redirect( add_query_arg( 'sessions-ended', 1 ) );
    exit;
} );

add_shortcode( 'wpide_logout_others', function () {
    if ( ! is_user_logged_in() ) {
        return '';
    }

    if ( isset( $_GET['sessions-ended'] ) ) {
        return '<p class="wpide-sessions-notice" role="status">You have been logged out everywhere else.</p>';
    }

    $others = max( 0, count( WP_Session_Tokens::get_instance( get_current_user_id() )->get_all() ) - 1 );

    if ( ! $others ) {
        return '<p class="wpide-sessions-notice">You are not logged in anywhere else.</p>';
    }

    return '<form method="post" class="wpide-logout-others">'
        . wp_nonce_field( 'wpide_logout_others', 'wpide_logout_others_nonce', true, false )
        . '<p>' . esc_html( sprintf( _n( 'You are logged in on %d other device or browser.', 'You are logged in on %d other devices or browsers.', $others ), $others ) ) . '</p>'
        . '<p><button type="submit">Log out everywhere else</button></p></form>';
} );

Notes

Shows how many other sessions are active, so members can spot logins they do not recognise.

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.