# Email Alert When a User's Role Changes

> Emails the site administrator whenever a user's role changes, which helps spot unexpected privilege changes.

- Type: PHP
- Runs: Run everywhere
- Category: [Email](https://wpide.com/library/category/email/)
- Tags: email, users, roles, security
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/email-notify-role-change/

## Code

```php
add_action( 'set_user_role', function ( $user_id, $role, $old_roles ) {
    if ( empty( $old_roles ) ) {
        return; // New user, not a change.
    }

    $user  = get_userdata( $user_id );
    $actor = wp_get_current_user();

    if ( ! $user ) {
        return;
    }

    wp_mail(
        get_option( 'admin_email' ),
        sprintf( 'Role changed for %s', $user->user_login ),
        sprintf(
            "The role of %1\$s changed from %2\$s to %3\$s.\nChanged by: %4\$s\nTime: %5\$s\n",
            $user->user_login,
            implode( ', ', (array) $old_roles ),
            $role,
            $actor->exists() ? $actor->user_login : 'system',
            wp_date( 'Y-m-d H:i:s' )
        )
    );
}, 10, 3 );
```

## Notes

Sent to the address in Settings > General. Changes made during user registration are ignored.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Email Alert When a User's 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/
