Last Logged In Sortable Column

The default Last Login column only applies to users who are currently logged in. The timestamp is deleted when the user logs out.

First, you need to save the timestamp when a user logs in. This will save it to user_meta.


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

To sort by this value you need to add a column to the users table and make it sortable.


// Add a new column to the users table
function add_last_login_column( $columns ) {
    $columns['wfls_last_login'] = 'Logged In'; // give this one a more accurate title
    $columns['last_login'] = 'Last Logged In'; // add a new one
    return $columns;
}
add_filter( 'manage_users_columns', 'add_last_login_column' );

// Display the last_login time for each user in the new column
function display_last_login_column( $value, $column_name, $user_id ) {
    if ( $column_name === 'last_login' ) {
        $last_login = get_user_meta( $user_id, 'last_login', true );
        if ( $last_login ) {
            return date( 'Y/m/d H:i', $last_login );
        }
        return 'Never';
    }
    return $value;
}
add_filter( 'manage_users_custom_column', 'display_last_login_column', 10, 3 );

// Make the column sortable
function make_last_login_column_sortable( $columns ) {
    $columns['last_login'] = 'last_login';
    return $columns;
}
add_filter( 'manage_users_sortable_columns', 'make_last_login_column_sortable' );

// Sort the users by last_login 
function sort_by_last_login( $query ) {
    if ( $query->get( 'orderby' ) === 'last_login' ) {
        $query->set( 'meta_key', 'last_login' );
        $query->set( 'orderby', 'meta_value_num' );
    }
}
add_action( 'pre_get_users', 'sort_by_last_login' );