0

I am using the function below to count posts for users (including custom post types). I am putting together a list of users and want to order them by this count function. The orderby options for the get_users() function are limited, and post_count doesn't include custom post types. How can I order my users using this function?

Function:

function foo_count_posts( $userid, $post_type = '', $post_status = 'publish') {
    global $wpdb;

    $query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND (post_type = 'post' OR post_type='foo') AND post_status = '$post_status'"; 
    $counter = $wpdb->get_var($query); 

    return apply_filters( 'get_usernumposts', $counter, $userid );  
}

Then I call the function to get the count:

echo foo_count_posts($user_id);

1 Answer 1

1

I assume the above function works well for you to get the count for the posts including the custom post types and you just need help in ordering the users using this count.

I assume you already have the list of user ids lets say the array $userids

Lets use asort and arsort to do so

Put the above code in the active theme's functions.php file and use the below in the file where you need to get the ordering

$arr = array();
foreach( $userids as $userid ) {
    $arr[$userid] = foo_count_posts($userid);
}

Now $arr is the array with userid as key and post count as the value

To get the ascending order use

asort($arr);
var_dump($arr);

To get the descending order use

arsort($arr);
var_dump($arr);

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.