Record when each user last logged in and show it as a sortable column on the Users screen, in your site's timezone.
// Save the login time as a UTC timestamp.
add_action( 'wp_login', function ( string $user_login, WP_User $user ): void {
update_user_meta( $user->ID, 'nahnu_last_login', time() );
}, 10, 2 );
add_filter( 'manage_users_columns', function ( array $columns ): array {
$columns['nahnu_last_login'] = 'Last login';
return $columns;
} );
add_filter( 'manage_users_custom_column', function ( string $output, string $column, int $user_id ): string {
if ( 'nahnu_last_login' !== $column ) {
return $output;
}
$time = (int) get_user_meta( $user_id, 'nahnu_last_login', true );
if ( ! $time ) {
return '<span aria-hidden="true">—</span><span class="screen-reader-text">Never</span>';
}
return sprintf(
'<span title="%s">%s ago</span>',
esc_attr( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $time ) ),
esc_html( human_time_diff( $time ) )
);
}, 10, 3 );
add_filter( 'manage_users_sortable_columns', function ( array $columns ): array {
$columns['nahnu_last_login'] = 'nahnu_last_login';
return $columns;
} );
add_action( 'pre_get_users', function ( WP_User_Query $query ): void {
if ( is_admin() && 'nahnu_last_login' === $query->get( 'orderby' ) ) {
$query->set( 'meta_key', 'nahnu_last_login' );
$query->set( 'orderby', 'meta_value_num' );
}
} );
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.
WordPress doesn’t record when users last logged in, which makes it hard to spot abandoned accounts that should be removed. This snippet saves the time of every login and adds a “Last login” column to the Users screen that you can sort by.
The wp_login action saves the current Unix timestamp to user meta each time someone logs in. The column shows how long ago that was, and hovering shows the exact date and time in the format and timezone from Settings → General, using wp_date().
The previous version stored the time with current_time( 'mysql' ), which is your site’s local time, then compared it with human_time_diff(), which works in UTC. On any site not set to UTC the “ago” text was off by the timezone difference. Storing a plain timestamp fixes that, and sorting now uses meta_value_num so it sorts numerically.
wp_login again until the user logs in fresh.Log out and back in, then open Users. Your row should say “1 min ago” or similar. Click the column title to sort.