Send administrators an email when their account logs in from an IP address it hasn't used before.
add_action( 'wp_login', function ( string $login, WP_User $user ): void {
if ( ! user_can( $user, 'manage_options' ) ) {
return;
}
$ip = sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? '' );
$known = array_values( array_filter( (array) get_user_meta( $user->ID, 'nahnu_known_ips', true ) ) );
if ( '' === $ip || in_array( $ip, $known, true ) ) {
return;
}
$first_time = ! $known;
$known[] = $ip;
update_user_meta( $user->ID, 'nahnu_known_ips', array_slice( $known, -10 ) );
// The first login after adding the snippet only records the address.
if ( $first_time ) {
return;
}
wp_mail(
$user->user_email,
sprintf( '[%s] New login to your account', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ),
sprintf(
"Your administrator account just logged in from a new IP address.\n\nIP address: %s\nBrowser: %s\nTime: %s\n\nIf this wasn't you, change your password now and check Users in wp-admin.",
$ip,
sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] ?? 'unknown' ),
wp_date( 'Y-m-d H:i T' )
)
);
}, 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.
If someone else logs in with an administrator’s password, the real owner should know straight away. This snippet emails administrators when their account signs in from an IP address it hasn’t used recently.
On wp_login, the snippet compares the IP address with the last ten addresses saved for that user. A known address does nothing. A new one is added to the list and triggers an email to the account owner with the address, browser and time.
The very first login after you add the snippet only records the address, so nobody gets an email just for installing it.
Log in as an administrator, then log in again from a different network, such as your phone’s mobile data. You should receive the alert.