Recent Login History on the Profile Screen
Records the last 10 logins for each user (time, IP address and browser) and lists them on their profile screen so they can spot logins they do not recognise.
Opens WPIDE on
Code
// How many logins to keep per user.
$wpide_login_history_size = 10;
add_action( 'wp_login', function ( $login, $user ) use ( $wpide_login_history_size ) {
$history = (array) get_user_meta( $user->ID, 'wpide_login_history', true );
$history = array_filter( $history, 'is_array' );
array_unshift( $history, array(
'time' => time(),
'ip' => isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '',
'ua' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ), 0, 200 ) : '',
) );
update_user_meta( $user->ID, 'wpide_login_history', array_slice( $history, 0, $wpide_login_history_size ) );
}, 10, 2 );
$wpide_login_history_table = function ( $user ) {
if ( get_current_user_id() !== $user->ID && ! current_user_can( 'edit_users' ) ) {
return;
}
$history = array_filter( (array) get_user_meta( $user->ID, 'wpide_login_history', true ), 'is_array' );
echo '<h2>Recent logins</h2>';
if ( ! $history ) {
echo '<p>No logins recorded yet.</p>';
return;
}
echo '<table class="widefat striped" style="max-width:900px"><thead><tr><th scope="col">When</th><th scope="col">IP address</th><th scope="col">Browser</th></tr></thead><tbody>';
foreach ( $history as $row ) {
printf(
'<tr><td>%1$s</td><td>%2$s</td><td>%3$s</td></tr>',
esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $row['time'] ) ),
esc_html( $row['ip'] ),
esc_html( $row['ua'] )
);
}
echo '</tbody></table>';
};
add_action( 'show_user_profile', $wpide_login_history_table );
add_action( 'edit_user_profile', $wpide_login_history_table );
Notes
Users see their own history; administrators also see it on other users' profiles. IP addresses are personal data, so mention this 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.