Email Alert When a User's Role Changes
Emails the site administrator whenever a user's role changes, which helps spot unexpected privilege changes.
Opens WPIDE on
Code
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 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.