DEV Community

loading...

How to display a user’s last login date in #WordPress admin

Mehluli Hikwa
I am a Digital Designer, Filmmaker and UI Development. When away from the digital world I'm either playing pool or attending to my bees - I'm a passionate hobbyist beekeeper.
・1 min read

A few weeks ago when a WordPress site I managed crushed, I had the client ask to view stats of user login times. By default WP does not support this.

First quick fix for such solutions is to install a plugin. Great option - I found this plugin called When Last Login. Its a lightweight plugin that allows you to see active users according to their last login time/date, with zero configuration - plug and play.

After installing it worked well. But being the developer I am, I was not settled having an extra plugin so I did some reading in the WP Codex and after a month I figured out a solution - plugin free.

If you’re familiar with adding code snippets to your site via functions.php or the code snippets plugin you can use this to add the user’s last login timestamp to the WP admin.

//Record user's last login to custom meta
add_action( 'wp_login', 'capture_user_login_time', 10, 2 );

function capture_user_login_time( $user_login, $user ) {
    update_user_meta( $user->ID, 'last_login', time() );
}

//Register new custom column with last login time
add_filter( 'manage_users_columns', 'user_last_login_time_column' );
add_filter( 'manage_users_custom_column', 'last_login_column', 10, 3 );

function user_last_login_time_column( $columns ) {
    $columns['last_login'] = 'Last Login';
    return $columns;
}

// Output last login column onto WP Front end
function last_login_column( $output, $column_id, $user_id ){
    if( $column_id == 'last_login' ) {
        $last_login = get_user_meta( $user_id, 'last_login', true );
        $date_format = 'M j, Y';
        $hover_date_format = 'F j, Y, g:i a';
        $output = $last_login ? '<div title="Last login: '.date( $hover_date_format, $last_login ).'">'.human_time_diff( $last_login ).'</div>' : 'No record';
    }
    return $output;
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)