wppaste
WordPress

count_users( string $strategy = 'time', int|null $site_id = null ): array

Since
3.0.0, 4.4.0, 4.9.0
Source
wp-includes/user.php:1324
Counts number of users who have each of the user roles.

Description

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.

Compatibility

WordPress
since 4.9.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$strategystringoptional
The computational strategy to use when counting the users.
Accepts either 'time' or 'memory'. Default 'time'.Default: 'time'
$site_idint|nulloptional
The site ID to count users for. Defaults to the current site.Default: null

Return value

array
User counts.
  • $total_usersint

    Total number of users on the site.
  • $avail_rolesint[]

    Array of user counts keyed by user role.

Performance profile

How much work a call to count_users() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Heavy

Reaches the database via ->get_col().

Scaling
Scales with input

The body loops, so the work grows with what you pass in.

Instructions
14–83

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 159.

Plugin surface
1 hook

Third-party callbacks on 'pre_count_users' run inside this call, and their cost is not bounded by anything here.

Called by
1

1 place in core call this, so the cost is paid more often than your own code shows.

What it touches

  • hookthird-party callbacksapply_filters()called directly
  • serializeserialisationmaybe_unserialize()called directly
  • sqldatabase query->get_col()called directly
  • cacheobject cachewp_cache_switch_to_blog()one call below count_users()

What one call costs · 10 distinct outcomes

One number would be a lie: the work depends on which branch runs. These are every distinct cost count_users() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
$pre !== null14apply_filters()
$pre !== null17get_current_blog_id(), apply_filters()
$pre === null && $strategy !== "time"42–43apply_filters(), ->get_blog_prefix(), ->get_col()
$pre === null && $strategy !== "time"45–46get_current_blog_id(), apply_filters(), ->get_blog_prefix(), ->get_col()
$pre === null && $strategy === "time" && !is_multisite()68–70apply_filters(), ->get_blog_prefix(), is_multisite(), wp_roles(), ->get_names(), ->get_row()
$pre === null && $strategy === "time" && !is_multisite()71–73get_current_blog_id(), apply_filters(), ->get_blog_prefix(), is_multisite(), wp_roles(), ->get_names(), ->get_row()
$pre === null && $strategy === "time" && is_multisite() && $site_id === false72–74apply_filters(), ->get_blog_prefix(), is_multisite(), get_current_blog_id(), wp_roles(), ->get_names(), ->get_row()
$pre === null && $strategy === "time" && is_multisite() && $site_id === false75–77get_current_blog_id(), apply_filters(), ->get_blog_prefix(), is_multisite(), get_current_blog_id(), wp_roles(), ->get_names(), ->get_row()
$pre === null && $strategy === "time" && is_multisite() && $site_id !== false78–80apply_filters(), ->get_blog_prefix(), is_multisite(), get_current_blog_id(), switch_to_blog(), wp_roles(), ->get_names(), restore_current_blog(), ->get_row()
$pre === null && $strategy === "time" && is_multisite() && $site_id !== false81–83get_current_blog_id(), apply_filters(), ->get_blog_prefix(), is_multisite(), get_current_blog_id(), switch_to_blog(), wp_roles(), ->get_names(), restore_current_blog(), ->get_row()

Across PHP versions

PHPCompiledExecutedBranchesNotes
8.6-dev15914–8317
8.515914–8317
8.415914–83173 fewer instructions than PHP 8.3
8.316214–8617
8.216214–8617
8.116214–8617
7.416214–8617

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Hooks and filters fired · 1

One hook fires while count_users() runs, in this order:

  1. apply_filters( pre_count_users )filterline 1344 (+20 into the body)

    Filters the user count before queries are run.

Uses · 8

Used by · 1

Source code

function count_users( $strategy = 'time', $site_id = null ) {	global $wpdb; 	// Initialize.	if ( ! $site_id ) {		$site_id = get_current_blog_id();	} 	/**	 * Filters the user count before queries are run.	 *	 * Return a non-null value to cause count_users() to return early.	 *	 * @since 5.1.0	 *	 * @param null|array $result   The value to return instead. Default null to continue with the query.	 * @param string     $strategy Optional. The computational strategy to use when counting the users.	 *                             Accepts either 'time' or 'memory'. Default 'time'.	 * @param int        $site_id  The site ID to count users for.	 */	$pre = apply_filters( 'pre_count_users', null, $strategy, $site_id ); 	if ( null !== $pre ) {		return $pre;	} 	$blog_prefix = $wpdb->get_blog_prefix( $site_id );	$result      = array(); 	if ( 'time' === $strategy ) {		if ( is_multisite() && get_current_blog_id() !== $site_id ) {			switch_to_blog( $site_id );			$avail_roles = wp_roles()->get_names();			restore_current_blog();		} else {			$avail_roles = wp_roles()->get_names();		} 		// Build a CPU-intensive query that will return concise information.		$select_count = array();		foreach ( $avail_roles as $this_role => $name ) {			$select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );		}		$select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";		$select_count   = implode( ', ', $select_count ); 		// Add the meta_value index to the selection list, then run the query.		$row = $wpdb->get_row(			"			SELECT {$select_count}, COUNT(*)			FROM {$wpdb->usermeta}			INNER JOIN {$wpdb->users} ON user_id = ID			WHERE meta_key = '{$blog_prefix}capabilities'		",			ARRAY_N		); 		// Run the previous loop again to associate results with role names.		$col         = 0;		$role_counts = array();		foreach ( $avail_roles as $this_role => $name ) {			$count = (int) $row[ $col++ ];			if ( $count > 0 ) {				$role_counts[ $this_role ] = $count;			}		} 		$role_counts['none'] = (int) $row[ $col++ ]; 		// Get the meta_value index from the end of the result set.		$total_users = (int) $row[ $col ]; 		$result['total_users'] = $total_users;		$result['avail_roles'] =& $role_counts;	} else {		$avail_roles = array(			'none' => 0,		); 		$users_of_blog = $wpdb->get_col(

Changelog

Introduced in 3.0.0. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

4.9.0
The $site_id parameter was added to support multisite.from the docblock
4.4.0
The number of users with no role is now included in the none element.from the docblock
3.0.0
Introduced.from the docblock

About this page

Parsed data
Generated from the wordpress-develop 6.8.8 tag, from src/wp-includes/user.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.