Im trying to order by post_count DESC but custom_post_type not working

function post_count_type($role, $number) {
$args = array(
    'post_type'     => array( 'custom_post_type' ),
    'orderby'       => 'post_count',
    'order'         => 'DESC',
    'role'          => $role,
    'number'        => $number
);
$users = get_users( $args );
$the_query = new WP_Query( $args );
    foreach ($users as $user) {
    echo 'html here...';
    }}

My function work for post_type : POST but not for custom post_type.
Sorry for my english.

1 Answer
1

You are using wrong approach

You are using the wrong approach for what you are trying to achieve. You are using the same arguments for both WP_Query and WP_User_Query (get_users eventually translates to WP_User_Query). The problem is that WP_Query doesn’t support orderby parameter post_count as one post is always equal to one post and WP_User_Query doesn’t support post_type as the user doesn’t have post type assigned to themselves.

This can’t be achieved using standard functions

In WP_User_Query it’s hardcoded that for user posts count, it looks only for post_type post. To achieve what you are trying to, you need to write a custom database query.

A custom solution

A standalone function to achieve this might look like this (please note I haven’t tested it so there might be a SQL typos or smth).

function get_users_by_post_count( $post_type="post" ) {
    global $wpdb;

    $users = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT {$wpdb->users}.ID, p.post_count
            FROM {$wpdb->users}  
            LEFT JOIN (
                SELECT post_author, COUNT(*) AS post_count 
                FROM {$wpdb->posts} WHERE post_type = %s
                GROUP BY post_author
            ) p ON {$wpdb->users}.id = p.post_author 
            ORDER BY p.post_count",
            $post_type
        )
    );

    return $users;
}

To use it simply call it like:

$users = get_users_by_post_count( 'custom_post_type' );

if ( ! empty( $users ) ) {
   foreach ( $users as $user ) {
       // there you have user ID and post_count
       echo $user->ID . ' has ' . $user->post_count . ' posts';
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *