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.
Opens WPIDE on
Code
$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 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.