# Email Alert When a New Administrator Appears

> Emails the site owner whenever an account is created as, or promoted to, administrator, which is often the first sign of a compromise.

- Type: PHP
- Runs: Run everywhere
- Category: [Security](https://wpide.com/library/category/security/)
- Tags: security, users, alerts
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/new-administrator-email-alert/

## Code

```php
$wpide_new_admin_alert = function ( $user_id ) {
    $user = get_userdata( $user_id );

    if ( ! $user ) {
        return;
    }

    $actor = wp_get_current_user();
    $site  = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );

    wp_mail(
        get_option( 'admin_email' ),
        sprintf( '[%s] New administrator: %s', $site, $user->user_login ),
        sprintf(
            "The account \"%s\" (%s) now has the administrator role on %s.\n\nChanged by: %s\nTime: %s\nIP: %s\n\nIf you did not expect this, review your users immediately.",
            $user->user_login,
            $user->user_email,
            home_url( '/' ),
            $actor->exists() ? $actor->user_login : 'unknown',
            wp_date( 'Y-m-d H:i:s T' ),
            isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'n/a'
        )
    );
};

add_action( 'set_user_role', function ( $user_id, $role, $old_roles ) use ( $wpide_new_admin_alert ) {
    if ( 'administrator' === $role && ! in_array( 'administrator', (array) $old_roles, true ) ) {
        $wpide_new_admin_alert( $user_id );
    }
}, 10, 3 );

add_action( 'add_user_role', function ( $user_id, $role ) use ( $wpide_new_admin_alert ) {
    if ( 'administrator' === $role ) {
        $wpide_new_admin_alert( $user_id );
    }
}, 10, 2 );
```

## How to use it

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