Home / Last Login Column
Duplicate Snippet

Embed Snippet on Your Site

Last Login Column

Add a column to the users table with the last time they logged in.

100+
Code Preview
php
<?php
// Please note: This snippet will only show the last login date & time AFTER the snippet is activated.
// The snippet has to be active to track the last login date & time.
// Add a column to the users table to display the last login time
add_filter( 'manage_users_columns', function ( $columns ) {
	$columns['last_login'] = __( 'Last Login' );
	return $columns;
} );
// Populate the last login column with data
add_filter( 'manage_users_custom_column', function ( $value, $column_name, $user_id ) {
	if ( 'last_login' === $column_name ) {
		$last_login = get_user_meta( $user_id, 'last_login', true );
		if ( $last_login ) {
			$value = date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $last_login );
		} else {
			$value = __( 'Never' );
		}
	}
	return $value;
}, 10, 3 );
// Record the last login time when a user logs in
add_action( 'wp_login', function ( $login, $user ) {
	update_user_meta( $user->ID, 'last_login', time() );
}, 10, 2 );

Comments

Add a Comment