Get an email whenever a new administrator account is created or an existing user is promoted to administrator.
function nahnu_alert_new_admin( int $user_id ): void {
static $sent = [];
if ( isset( $sent[ $user_id ] ) ) {
return;
}
$sent[ $user_id ] = true;
$user = get_userdata( $user_id );
$by = wp_get_current_user();
if ( ! $user ) {
return;
}
wp_mail(
get_option( 'admin_email' ),
sprintf( '[%s] New administrator: %s', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), $user->user_login ),
sprintf(
"A user now has the Administrator role.\n\nUsername: %s\nEmail: %s\nChanged by: %s\nIP address: %s\nTime: %s\n\nIf you didn't expect this, check Users in wp-admin straight away.",
$user->user_login,
$user->user_email,
$by->exists() ? $by->user_login : 'Not logged in',
sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? 'unknown' ),
wp_date( 'Y-m-d H:i T' )
)
);
}
add_action( 'set_user_role', function ( int $user_id, string $role, array $old_roles ): void {
if ( 'administrator' === $role && ! in_array( 'administrator', $old_roles, true ) ) {
nahnu_alert_new_admin( $user_id );
}
}, 10, 3 );
add_action( 'add_user_role', function ( int $user_id, string $role ): void {
if ( 'administrator' === $role ) {
nahnu_alert_new_admin( $user_id );
}
}, 10, 2 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Creating a hidden administrator is one of the first things attackers do after breaking in. An email the moment it happens lets you react in minutes instead of weeks.
WordPress fires set_user_role when a user’s role is set, including when a new user is created, and add_user_role when a role is added on top of others. If the new role is Administrator and the user didn’t already have it, the snippet emails the site’s admin address with who was promoted, who did it, their IP address and the time.
A static list stops duplicate emails when both hooks fire for the same user in one request.
Promote a test user to Administrator. You should receive an email within a minute.