1

I have been searching high and low for a way to count the amount of results from a get_users query.

Most of what I found is to count the total number of posts in a post query, but nothing for counting the total number of users in the get_users query.

Can someone point it out for me? Thanks a lot.

1

when you use get_users() it retrieves an array of users matching the criteria given in $args which means you can simply use PHP's count() function e.g:

$users = get_users($args);
$number_of_users = count($users);
  • 1
    That answer is incorrect as get_users() only returns the requested number of results, i.e. 10, 20 etc... There may be more. – unknowndomain Sep 12 '12 at 23:10
  • umm, that is true if you set the number parameter but if not (which obviously is the case here) then This answer is correct! – Bainternet Sep 13 '12 at 8:58
1

This looks like the proper way. Similar to Gruffy's answer, but without the added steps.

Note that get_users() uses WP_User_Query too, but removes the total result. Therefore this method is not any slower.

$user_query = new WP_User_Query(array(
    'number' => 15,
    'paged' => 1
));

$users = (array) $user_query->get_results(); // return: Array of WP_User objects

count($users); // return: 15

$user_query->get_total(); // return: 86
0

Here is how I implemented this:

function getUsers($args = array(), $count = false)
{
    // Default behaviour is to return full user information
    $method = 'get_results';

    // If count is true then change the WP_User_Query method
    // and limit the fields SELECT'd to 'ID' to speed up the query
    if($count === true) {
        $method = 'get_total';
        $args['fields'] = 'ID';
    }

    $userQuery = new WP_User_Query($userArgs);

    return call_user_func(array($userQuery, $method));
}

Usage:

$args = array('role' => author,
              'meta_key' => 'foo',
              'meta_value' => 'bar'
        );

// Returns (array) WP_User objects (a la get_users())
$users = getUsers($args);

// Returns (int) number of of users matched by $args
$count = getUsers($args, true);

Aside from being more compact / reusable than $users = get_users($args); $count = count($users); it ensures that if all you want is the total number then it will fetch the minimum required from the DB to achieve this.

0

Try the function below to get the count of all users, and user counts based on user roles, in an array:

count_users();

Output comes like this:

Array (
    [total_users] => 32
    [avail_roles] => Array (
        [administrator] => 1
        [subscriber] => 28
        [sub_administrator] => 1
        [editor] => 2
    )
)

More information can be found here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.