"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.
Opens WPIDE on
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
- 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.