count_users()
Count number of users who have each of the user roles.
Assumes there are neither duplicated nor orphaned capabilities meta_values. Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query() Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users. Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
1 time — 0.0375981 sec (extremely slow) | 50000 times — 1750.27 sec (extremely slow) | PHP 7.3.12, WP 5.4
Hooks from the function
Return
Array
. User counts.
Usage
count_users( $strategy, $site_id );
- $strategy(string)
- The computational strategy to use when counting the users. Accepts either 'time' or 'memory'.
Default: 'time' - $site_id(int|null)
- The site ID to count users for.
Default: current site
Examples
#1 Example, the output of posts about the number of users in the context of their roles:
$result = count_users(); $roles = []; foreach( $result['avail_roles'] as $role => $count ){ $roles[] = "{$role} ({$count})"; } echo sprintf( 'There are %s users on the site, including: %s.', $result['total_users'], implode( ', ', $roles ) );
The result will be such inscription:
There are 2 users on the site, including: administrator (1), subscriber (1).
#2 What the function outputs [auto-translate]
print_r( count_users() ); /* Array ( [total_users] => 474 [avail_roles] => Array ( [administrator] => 1 [subscriber] => 473 [none] => 0 ) ) */
Notes
- Global. wpdb. $wpdb WordPress database abstraction object.
Changelog
Since 3.0.0 | Introduced. |
Since 4.4.0 | The number of users with no role is now included in the none element. |
Since 4.9.0 | The $site_id parameter was added to support multisite. |