The count_users() WordPress PHP function is used to count the number of users who possess each of the user roles. It assumes that there are neither duplicated nor orphaned capabilities meta_values and that role names are unique phrases. This function is either CPU-intensive (using $strategy = ‘time’) or memory-intensive (using $strategy = ‘memory’).
Usage
Here’s an example of how you might use the function:
// Count users using default strategy ('time') $result = count_users(); echo 'There are ', $result['total_users'], ' total users'; foreach( $result['avail_roles'] as $role => $count ) echo ', ', $count, ' are ', $role, 's';
In this example, the function will count the total users and users per role, and then print these counts.
Parameters
- $strategy (string, optional): The computational strategy to use when counting the users. Accepts either ‘time’ or ‘memory’. Default ‘time’.
- $site_id (int|null, optional): The site ID to count users for. Defaults to the current site.
More Information
See WordPress Developer Resources: count_users()
Examples
Count Users with Default Strategy
This example counts users using the default strategy (‘time’).
$result = count_users(); echo 'There are ', $result['total_users'], ' total users'; foreach( $result['avail_roles'] as $role => $count ) echo ', ', $count, ' are ', $role, 's';
Count Users with Memory Strategy
This example uses the ‘memory’ strategy to count users.
$result = count_users('memory'); echo 'There are ', $result['total_users'], ' total users'; foreach( $result['avail_roles'] as $role => $count ) echo ', ', $count, ' are ', $role, 's';
Count Users for a Specific Site
This example counts users for a specific site.
$result = count_users('time', 2); echo 'There are ', $result['total_users'], ' total users for site 2'; foreach( $result['avail_roles'] as $role => $count ) echo ', ', $count, ' are ', $role, 's';
Count Only Administrators
This example counts only administrators.
$result = count_users(); echo 'There are ', $result['avail_roles']['administrator'], ' administrators';
Count and Display All Roles
This example counts and displays all roles.
$result = count_users(); foreach( $result['avail_roles'] as $role => $count ) echo 'There are ', $count, ' ', $role, 's';
In all examples, the output will be similar to:
“There are 199 total users, 11 are administrators, 4 are contributors.”