On a recent multisite project, I needed to grab all the authors from across the network and display them in order based on their post counts. Traditionally, when using WP_User_Query there is an orderby argument that can be used to sort the users by their post count. However, we were pulling the users on the main site within the network and none of the users had any posts on that site. This meant that the orderby results would have been useless for this display.
As an alternative, we decided to gather the post counts from across the network and save the total as usermeta. We could then sort by that count using the “meta_value” option for the orderby argument within our WP_User_Query.
To accomplish this we’ll need to:
- Have all authors within the network added as a subscriber on the main site
- Get all the blogs and post counts associated with each user
- Sum up the post counts from each blog and save as user meta
- Set up a cron job to run this function daily
- Full code (as plugin)
- Application
Have all authors added to main site
I started out by using the Multisite User Management plugin to have all the authors throughout the network added as a subscriber on my main site. This allowed me to get all my authors by doing a single WP_User_Query of the subscribers on the main site.
Get the blogs and post counts associated with each user
For each user, I then needed to find the blogs that they were associated with and grab their post counts from each blog. For this, I used the get_blogs_of_user() function, looped through the results and added the counts from each site to an array.
Sum the counts and save the user meta
I was then able to total up all the items within the array to get a single value to be saved for the user meta. For this, I used the array_sum() function. The resulting total was then added as user meta for that user using the update_user_meta() function.
* At this point, I also used a string pad on this result to help when comparing the values. This, for example, turned a result of “9” into “009”. If we didn’t do this, when our query output the results, an author with a count of “9” would display before an author with a count of “200”
Setup cron job to update the counts daily
Finally, since these counts would always be changing, I needed to set up a cron job allowing the function to be run daily and update the post counts.
You can find the complete code below. This single file can be used as a standalone plugin.
Application
I was then able to use that data to sort my WP_User_Query by using the “meta_value” orderby argument.
Leave a Reply