Log Users Out Everywhere When Their Role Changes
Ends all of a user's active sessions as soon as an administrator changes or removes their role, so a demoted account cannot keep using old access.
Opens WPIDE on
Code
$wpide_end_sessions = function ( $user_id ) {
if ( (int) $user_id !== get_current_user_id() ) {
WP_Session_Tokens::get_instance( (int) $user_id )->destroy_all();
}
};
add_action( 'set_user_role', function ( $user_id, $role, $old_roles ) use ( $wpide_end_sessions ) {
if ( $old_roles && ! in_array( $role, (array) $old_roles, true ) ) {
$wpide_end_sessions( $user_id );
}
}, 10, 3 );
add_action( 'remove_user_role', function ( $user_id ) use ( $wpide_end_sessions ) {
$wpide_end_sessions( $user_id );
} );
Notes
Your own sessions are kept when you change your own role, so you are not logged out mid-edit.
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.