John Davidson

php - Wordpress: sort registered user Posts column by count in the admin dashboard?

0 comments
Message:


I have a functions code, that sorts my registration date in the Wordpress admin dashboard, when "All Users - > Users" is selected:


/*
* Make our "Registration date" column sortable
* @param array $columns Array of all user sortable columns {column ID} => {orderby GET-param}
*/
add_filter( 'manage_users_sortable_columns', 'rudr_make_registered_column_sortable' );

function rudr_make_registered_column_sortable( $columns ) {
return wp_parse_args( array( 'registration_date' => 'registered' ), $columns );
}

My question is how can I make the same for Posts?


Basically I want to sort Posts column by count to see which users made the most posts.


I know I probably need to make slight changes in the above code, but been struggling for a while.


Need help.



My Answer:
I display the list of registered users. You can modify this code to sort the Posts column by count instead. Here is the modified code:

php
// Sort registered user Posts column by count in admin dashboard
function custom_user_sortable_columns( $columns ) {
$columns['post_count'] = 'Post Count';
return $columns;
}
add_filter( 'manage_users_sortable_columns', 'custom_user_sortable_columns' );

function custom_user_column_sort( $query ) {
if ( ! is_admin() ) {
return;
}

$orderby = $query->get( 'orderby' );

if ( 'post_count' == $orderby ) {
$query->set( 'meta_key', 'post_count' );
$query->set( 'orderby', 'meta_value_num' );
}
}
add_action( 'pre_get_users', 'custom_user_column_sort' );

function custom_user_column_data( $value, $column_name, $user_id ) {
if ( 'post_count' == $column_name ) {
$post_count = count_user_posts( $user_id );
return $post_count;
}
return $value;
}
add_filter( 'manage_users_custom_column', 'custom_user_column_data', 10, 3 );


This code adds a new sortable column "Post Count" to the user list in the admin dashboard. It then sorts the users based on the count of their posts when this column is selected for sorting. The `custom_user_column_data` function retrieves the post count for each user and displays it in the column.

You can add this code to your theme's `functions.php` file or create a custom plugin for it. Make sure to test it thoroughly before using it on a live site.

Rate this post

3 of 5 based on 2868 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us