# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Login](https://wpide.com/library/category/login/)
- Tags: sessions, roles, security
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/logout-on-role-change/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Log Users Out Everywhere When Their Role Changes" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
