Show Your Previous Login Time After Logging In
Greets users in the admin with the date, time and IP address of their previous login, so they can spot logins they do not recognize.
Opens WPIDE on
Code
add_action( 'wp_login', function ( $login, $user ) {
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
update_user_meta( $user->ID, 'wpide_previous_login', get_user_meta( $user->ID, 'wpide_current_login', true ) );
update_user_meta( $user->ID, 'wpide_current_login', array( 'time' => time(), 'ip' => $ip ) );
update_user_meta( $user->ID, 'wpide_show_login_notice', 1 );
}, 10, 2 );
add_action( 'admin_notices', function () {
$user_id = get_current_user_id();
if ( ! $user_id || ! get_user_meta( $user_id, 'wpide_show_login_notice', true ) ) {
return;
}
delete_user_meta( $user_id, 'wpide_show_login_notice' );
$previous = get_user_meta( $user_id, 'wpide_previous_login', true );
if ( empty( $previous['time'] ) ) {
return;
}
printf(
'<div class="notice notice-info is-dismissible"><p>Welcome back. Your previous login was on %1$s from IP %2$s. Not you? <a href="%3$s">Change your password</a>.</p></div>',
esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $previous['time'] ) ),
esc_html( $previous['ip'] ? $previous['ip'] : 'unknown' ),
esc_url( admin_url( 'profile.php#password' ) )
);
} );
Notes
Stores the IP address of the last two logins in user meta; mention it in your privacy policy.
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.