Add WordPress Last Login User Column

Add WordPress Last Login User Column

[ad_1]

How to add last logged in user column in WordPress?

Today I’m going to show you how to find out the last time a user logged into your website.

Step 1. Save last login in user meta

Before displaying the last login date for each user account, we need to collect it each time the user logs into your website.

add_action( 'wp_login', 'misha_collect_login_timestamp', 20, 2 );
 
function misha_collect_login_timestamp( $user_login, $user ) {
 
	update_user_meta( $user->ID, 'last_login', time() );
 
}

You copy this code into the functions.php file of the current theme.

This code allows WordPress to start logging into the wp_usermeta table each time a user logs into your site.

Step 2. View Information on All Users Page

add_filter( 'manage_users_columns', 'misha_add_last_login_column' );
add_filter( 'manage_users_custom_column', 'misha_last_login_column', 10, 3 );
 
function misha_user_last_login_column( $columns ) {
 
	$columns['last_login'] = 'Last Login'; // column ID / column Title
	return $columns;
 
}
 
function misha_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="j M, Y";
 
		$output = $last_login ? date( $date_format, $last_login ) : '-';
 
	}
 
	return $output;
 
}

Add sortable for columns

This step is optional but is very useful as it allows you to schedule times if you want to know which users have been active recently.

add_filter( 'manage_users_sortable_columns', 'misha_sortable_columns' );
add_action( 'pre_get_users', 'misha_sort_last_login_column' );
 
function misha_sortable_columns( $columns ) {
 
	return wp_parse_args( array(
	 	'last_login' => 'last_login'
	), $columns );
 
});
 
function misha_sort_last_login_column( $query ) {
 
	if( !is_admin() ) {
		return $query;
	}
 
	$screen = get_current_screen();
 
	if( isset( $screen->id ) && $screen->id !== 'users' ) {
		return $query;
	}
 
	if( isset( $_GET[ 'orderby' ] ) && $_GET[ 'orderby' ] == 'last_login' ) {
 
		$query->query_vars['meta_key'] = 'last_login';
		$query->query_vars['orderby'] = 'meta_value';
 
	}
 
	return $query;
 
} );

Epilogue

With just the simple code above, you have displayed the last logged in user column in WordPress.

If you find it interesting, you can follow the wordpress tips section to learn more new knowledge.

Follow the fanpage to receive the latest articles: Hocwordpress Group

I wish you to have interesting and interesting knowledge about wordpress!

0
0
voice

Rate Items



[ad_2]

Recommended Posts