0

To assist with managing a WordPress install with a large number of users, is there a simple way to include the date the user registered and they date they last logged in as additional columns on the user list page? Can these columns be sortable?

1 Answer 1

1

The registration date is kept in the wp_users table, so that's easy to get.

The last login date is a little trickier. Most plugins which implement a last login date column create a custom meta field to store it (in wp_usermeta), update it every time the user logs in, and retrieve it for display on the user list screen. However, WordPress already stores login dates (and related session information) in a meta field called session_tokens, so if you don't need last login date to be sortable, you can extract the last login date from this array rather than storing it separately.

// 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' ), $columns );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.