The WP_User_Query::parse_orderby()
actually supports sorting by the number of posts, but because WP_User_Query::parse_orderby()
limits by what users can be sorted, accomplishing a custom sort is a bit of a hack.
Here’s the workaround I’ve created (semi-tested):
add_filter( 'manage_users_sortable_columns', static function ( $columns ) {
$columns['articles_count'] = array(
'articles_count',
false,
__( 'Articles' ),
__( 'Table ordered by number of articles.' ),
);
return $columns;
} );
/**
* Because `parse_orderby()` will discard 'articles_count',
* set it to `post_count`, and create a custom query var for
* reference later.
*/
add_action( 'pre_get_users', static function ( $query ) {
if ( 'articles_count' !== $query->get( 'orderby' ) ) {
return;
}
$query->set( 'orderby', 'post_count' );
$query->set( 'sort_articles_count', true );
} );
/**
* Check for our custom query var, and change the SQL
* for sorting users.
*/
add_action( 'pre_user_query', static function ( $query ) {
if ( ! $query->get( 'sort_articles_count' ) ) {
return;
}
$search = get_posts_by_author_sql( 'post' );
$replace = get_posts_by_author_sql( 'articles' );
$query->query_from = str_replace( $search, $replace, $query->query_from );
} );