0

I created a new column in the Users Admin Tab where it says how many Listings an user has.

//// ADD THE NEW COLUMN
add_filter( 'manage_users_columns', 'add_listing_count_column' );
function add_listing_count_column( $columns ) {
    $columns['Listings'] = 'Listings'; // 
    return $columns;}


// FILL THE NEW COLUMN
add_filter( 'manage_users_custom_column', 'add_listing_count_column_row', 10, 3 );
function add_listing_count_column_row( $row_output, $column_id_attr, $user_id ) {
if ( $column_id_attr == 'Listings') {
        return count_user_posts( $user_id, 'job_listing' );
    }
    return $row_output;}

now I'm trying to sort the numbers. But it keeps sorting by username...

// MAKE THE NEW COLUMN SORTABLE
add_filter( 'manage_users_sortable_columns', 'add_listing_count_column_sortable');
function add_listing_count_column_sortable( $columns ) {
    return wp_parse_args( array( 'Listings' => 'Listings' ), $columns );}

1 Answer 1

0
  • ✅ You've added the column!
  • ✅ You've told the admin UI it's a sortable column!
  • ❌ You didn't implement the sorting of the user query.

It's not enough to tell WP Admin that you have a sortable column, how is it meant to know how to sort it ¯\_(ツ)_/¯! It's not that clever, it has no idea what your function that displays the content is displaying or what kind of HTML it'll return it just calls it and trusts it'll do the job. How do we know the output from add_listing_count_column_row isn't a youtube video or a random number?

The sorting itself is done via the database, the PHP just creates the query and displays the results. It isn't going to get the results of every user and sort them in PHP, that would limit the number of users in WordPress to a single page of results.

So instead, use the pre_get_users hook that same way you would use pre_get_posts, look for the URL get parameter it added to indicate the sorting and direction, double check is_admin is true so you don't mess up the frontend, and modify the WP_User_Query to sort the users using the sorting/order query variables in the WP_User_Query documentation.

Note that this will lead you to a new and separate question though that you need to ask a brand new question: "How do I sort a WP_User_Query by a users specific post type count?"

1
  • add_listing_count_column_row is a number.. Is the number of listings each user has...
    – AFM
    Nov 4, 2021 at 0:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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