I've added the code found here and slightly modified it so that the "Last Logged In" column is sortable but it doesn't sort the column correctly when I click it, can anyone see anything wrong with the code?
Thanks
// add two columns to the user list page
add_filter( 'manage_users_columns', 'my_manage_users_columns' );
function my_manage_users_columns( $columns ) {
$columns['registration_date'] = 'Registered';
$columns['last_login_date'] = 'Last Logged In';
return $columns;
}
// provide data for the two added columns
add_filter( 'manage_users_custom_column', 'my_manage_users_custom_column', 10, 3 );
function my_manage_users_custom_column( $row_output, $column_id_attr, $user ) {
$date_format = 'Y/m/d \a\t g:i a';
$d1 = 0;
switch ( $column_id_attr ) {
case 'registration_date':
$d1 = strtotime(get_userdata($user)->user_registered);
break;
case 'last_login_date':
$session_tokens = get_user_meta( $user, 'session_tokens', true );
if (!empty($session_tokens)) {
$d1 = max(array_column(array_values($session_tokens),'login'));
}
break;
default:
}
if ($d1 > 0) {
$d2 = new DateTime("@$d1");
return $d2->setTimezone(wp_timezone())->format($date_format);
}
return $row_output;
}
// make the registration date column sortable
add_filter( 'manage_users_sortable_columns', 'my_manage_users_sortable_columns' );
function my_manage_users_sortable_columns( $columns ) {
return wp_parse_args( array( 'registration_date' => 'registered', 'last_login_date' => 'Last Logged In' ), $columns );
}
add_action( 'pre_user_query', 'misha_users_by_date_registered_by_default' );
function misha_users_by_date_registered_by_default( $query ) {
global $pagenow;
if ( is_admin() && 'users.php' == $pagenow ) {
$query->query_orderby = 'ORDER BY user_registered DESC';
}
return $query;
}
session_data
field is for, the column it tries to add doesn't do what they thought it does. Even if you fix sorting that data, it is not reliable because WP deletes it when users log out or it expires, it's only used for storing active sessions. Anybody who clicks the logout link will have an untraceable loginupdate_user_meta
, and order by that instead.