Get And Display The Total Registered Users With WordPress Roles

As a site owner with a big number of registered users and have some additional roles, perhaps you want to display the total registered users for each roles. WordPress have provided a function count_users and a global variable $wp_roles for information of each roles to make it simple. The count_users returns an array data with total users for each role and the total of all registered users.

This PHP function:

$count = count_users();

will provide results the total users for each role with the roles index, not the roles name.

Array (
    [total_users] => 7
    [avail_roles] => Array (
        [administrator] => 1
        [author] => 1
        [subscriber] => 5

By using the WP Roles global variable:

global $wp_roles;
$role_names = $wp_roles->role_names;

will returns the roles name for further use:

    [administrator] => Administrator
    [editor] => Editor
    [author] => Author
    [contributor] => Contributor
    [subscriber] => Subscriber

In this case we want to display the total users with the role name, not the role index. Adding zero for empty role users.

foreach ( $role_names as $role => $name ) {
    $total = isset($count['avail_roles'][$role]) ? $count['avail_roles'][$role] : 0;
    echo $role_names[$role] . ': ' . $total . '
'; }

The above code will results:

Administrator: 1
Editor: 0
Author: 1
Contributor: 0
Subscriber: 5		

That’s it. That’s how to display the total users for each role in your template file. If you want a premium WordPress plugin for displaying the total registered users, the total social followers, subscribers or likes, we have provided the Total Users Pro.

Create Comment

Your email address will not be published. Required fields are marked *