Email Alert When an Administrator Logs In
Sends an email to the site admin address every time an administrator account logs in, with the time, IP address and browser.
Opens WPIDE on
Code
add_action( 'wp_login', function ( $user_login, $user ) {
if ( ! user_can( $user, 'manage_options' ) ) {
return;
}
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
$browser = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : 'unknown';
$site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
$subject = sprintf( '[%s] Administrator login: %s', $site, $user->user_login );
$message = sprintf(
"The administrator account \"%s\" just logged in to %s.\n\nTime: %s\nIP address: %s\nBrowser: %s\n\nIf you do not recognize this login, change the password and review your users.",
$user->user_login,
home_url( '/' ),
wp_date( 'Y-m-d H:i:s T' ),
$ip,
$browser
);
wp_mail( get_option( 'admin_email' ), $subject, $message );
}, 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.