I have been searching high and low for a way to count the amount of results from a get_users query.
Most of what I found is to count the total number of posts in a post query, but nothing for counting the total number of users in the get_users query.
Can someone point it out for me? Thanks a lot.
when you use
get_users()
it retrieves an array of users matching the criteria given in$args
which means you can simply use PHP’scount()
function e.g:Bainternet’s answer gives you the number of users for one query and doesn’t help if you need multiple pages of users.
If you have thousands of users that’s not what you want. You can use WP_User_Query much the same way you use WP_Query for posts. It’s very similar to get_users — same arguments, but different features and usage.
Most importantly you can get the total number of users who match your criteria without actually returning all of the results (and potentially hitting memory limits).
Usage
Examples:
Here is how I implemented this:
Usage:
Aside from being more compact / reusable than
$users = get_users($args); $count = count($users);
it ensures that if all you want is the total number then it will fetch the minimum required from the DB to achieve this.Try the function below to get the count of all users, and user counts based on user roles, in an array:
Output comes like this:
More information can be found here.