diff --git a/src/wp-includes/user-functions.php b/src/wp-includes/user-functions.php index 2b8151fd3d..5e56f53947 100644 --- a/src/wp-includes/user-functions.php +++ b/src/wp-includes/user-functions.php @@ -758,6 +758,7 @@ function count_users($strategy = 'time') { 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. @@ -773,11 +774,11 @@ function count_users($strategy = 'time') { } } + $role_counts['none'] = (int) $row[$col++]; + // Get the meta_value index from the end of the result set. $total_users = (int) $row[$col]; - $role_counts['none'] = ( $total_users - array_sum( $role_counts ) ); - $result['total_users'] = $total_users; $result['avail_roles'] =& $role_counts; } else { diff --git a/tests/phpunit/tests/user/countUsers.php b/tests/phpunit/tests/user/countUsers.php index 257a045349..d3192bbfa5 100644 --- a/tests/phpunit/tests/user/countUsers.php +++ b/tests/phpunit/tests/user/countUsers.php @@ -140,6 +140,41 @@ class Tests_User_CountUsers extends WP_UnitTestCase { } + /** + * @ticket 34495 + * + * @dataProvider data_count_users_strategies + */ + public function test_count_users_is_accurate_with_multiple_roles( $strategy ) { + + // Setup users + $admin = self::factory()->user->create( array( + 'role' => 'administrator', + ) ); + $editor = self::factory()->user->create( array( + 'role' => 'editor', + ) ); + + get_userdata( $editor )->add_role( 'author' ); + + $this->assertEquals( array( + 'editor', + 'author' + ), get_userdata( $editor )->roles ); + + // Test user counts + $count = count_users( $strategy ); + + $this->assertEquals( 3, $count['total_users'] ); + $this->assertEquals( array( + 'administrator' => 2, + 'editor' => 1, + 'author' => 1, + 'none' => 0, + ), $count['avail_roles'] ); + + } + function data_count_users_strategies() { return array( array(