WP Developers can retrieve the number of registered users when developing plugins or themes. WordPress introduced the count_users function to get the count of users when you need it. Also, the count_users function will give a detailed user count based on user roles.
In this WordPress tutorial, we’re going to try the count_users function in a working environment.
To get more into it, I’m going to make a shortcode out of the count_users
function so that you can print the number anywhere you want using simple code.
We’ll have an extra step to make this function a shortcode, but you can think of it as a bonus tutorial.
How to Count Users in WordPress using the count_users
function?
When you are running the count_users function, this function will return an array.
Returned array from the count_users
function has a total_users
key that contains the number of all users.
But what if you need to count users for each user role? Well, the returned array has that data too!
avail_roles
is the key that provides an array value that contains the user count for each available user role.
Example of the count_users
function output (fresh WordPress installation):
Array
(
[total_users] => 1
[avail_roles] => Array
(
[administrator] => 1
[none] => 0
)
)
How to print the count_users
function output in a shortcode?
To add a shortcode in WordPress, you must use the add_shortcode
function to register it.
The add_shortcode
function gets two parameters, a unique tag and a callback which is the name of our custom user counter function.
Add the below codes to your current theme’s functions.php
file or your custom plugin:
add_shortcode('count-users', 'my_custom_user_counter');
function my_custom_user_counter() {
return count_users()["total_users"];
}
After adding this code to your WordPress, you can use it inside the WordPress editor or within the do_shortcode
function:
[count-users]
I encourage you to create your own plugin to test codes in a more organized way.
If you do not know how to create a Simple WordPress Plugin, read my tutorial:
written by Mehdi Nazari about in WordPress WordPress Functions WordPress Plugin Development WordPress Theme Development
What do you think about "How to Count Users in WordPress (Example + Shortcode)"?