0

I created a new column in the Users Admin Tab called "Listings". Each line is a number which means 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;}

I want to make that column sortable.. But it keeps sorting by username... Any idea what could it be?

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

 add_action( 'pre_get_users', 'smartwp_sort_last_login_column' );
function smartwp_sort_last_login_column( $query ) {
    if ( ! is_admin() ) {
        return $query;
    }
     $screen = get_current_screen();
    if ( isset( $screen->id ) && $screen->id !== 'users' ) {
        return $query;
    }
     if ( isset( $_GET[ 'orderby' ] ) && $_GET[ 'orderby' ] == 'Listings' ) {
        $query->query_vars['orderby'] = 'post_count';
    }
     return $query;
}


thank you

1 Answer 1

0

If orderby equals post_count, WordPress will always work with posts from the default post type post. What you can do is, try to modify that part of the query for this specific case.

Something like this should work:

add_filter( 'query', 'smartwp_sort_last_login_column_query' );
function smartwp_sort_last_login_column_query( $query ) {
    if ( ! is_admin() ) {
        return $query;
    }

    $orderby = isset( $_GET[ 'orderby' ] ) ? $_GET[ 'orderby' ] : false;

    if ( $orderby !== 'Listings' ) {
        return $query;
    }

    if ( stripos( $query, 'SELECT post_author, COUNT(*) as post_count' ) !== false ) {
        $query = str_replace( '( post_type = \'post\' AND', '( post_type = \'job_listing\' AND', $query );
    }

    return $query;
}

What this does is tell WordPress to count the posts from the custom post type job_listing. Please note, that this only works for your specific case.

Make sure to fully test it, as this is the query hook, which is executed on every database query WordPress makes.

2
  • thank you! it worked :)
    – AFM
    Nov 8, 2021 at 19:14
  • Great! Please mark the answer as "accepted" so it may help other users. Nov 8, 2021 at 19:15

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.