count_users()
Counts the total number of users, dividing them by roles (administrators, subscribers).
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
Returns
Array. Data about the number of users. An array of the following form:
Array( [total_users] => 2 [avail_roles] => Array( [administrator] => 1 [subscriber] => 1 ) )
Usage
$counts = count_users( $strategy );
- $strategy(string)
- Can be:
timeormemory.
Default: 'time' - $site_id(int) (since version 4.9)
- Site ID, for multisite mode.
Default: null
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
print_r( count_users() ); /* Array ( [total_users] => 474 [avail_roles] => Array ( [administrator] => 1 [subscriber] => 473 [none] => 0 ) ) */
Notes
- Global. wpdb.
$wpdbWordPress 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. |