Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.