Skip to content

Instantly share code, notes, and snippets.

@someguy9
Last active March 14, 2022 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save someguy9/e8ce146506507a9a222f6c362795ff77 to your computer and use it in GitHub Desktop.
Save someguy9/e8ce146506507a9a222f6c362795ff77 to your computer and use it in GitHub Desktop.
Saves a WordPress user's last login and puts it in a sortable column in the WordPress dashboard
<?php
//Record user's last login to custom meta
add_action( 'wp_login', 'smartwp_capture_login_time', 10, 2 );
function smartwp_capture_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', 'smartwp_user_last_login_column' );
add_filter( 'manage_users_custom_column', 'smartwp_last_login_column', 10, 3 );
function smartwp_user_last_login_column( $columns ) {
$columns['last_login'] = 'Last Login';
return $columns;
}
function smartwp_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;
}
//Allow the last login columns to be sortable
add_filter( 'manage_users_sortable_columns', 'smartwp_sortable_last_login_column' );
add_action( 'pre_get_users', 'smartwp_sort_last_login_column' );
function smartwp_sortable_last_login_column( $columns ) {
return wp_parse_args( array(
'last_login' => 'last_login'
), $columns );
}
function smartwp_sort_last_login_column( $query ) {
if( !is_admin() ) {
return $query;
}
$screen = get_current_screen();
if( isset( $screen->base ) && $screen->base !== '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;
}
//Add [lastlogin] shortcode
function smartwp_lastlogin_shortcode( $atts ) {
$atts = shortcode_atts(
array(
'user_id' => false,
), $atts, 'lastlogin' );
$last_login = get_the_author_meta('last_login', $atts['user_id']);
if( empty($last_login) ){ return false; };
$the_login_date = human_time_diff($last_login);
return $the_login_date;
}
add_shortcode( 'lastlogin', 'smartwp_lastlogin_shortcode' );
@IanDelMar
Copy link

$query in smartwp_sort_last_login_column( $query ) is passed by reference. There's no need to return $query.

Also, note that $screen->id is users-network for network admins.

@someguy9
Copy link
Author

@IanDelMar thank you, going to modify the code with these comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment