On my last tutorial, I have shown how to retrieve the total user count in WordPress. Today in this tutorial, I will show you how to create a list of users in WordPress. These is fairly simple and easy to understand. By default WordPress has quite a few different types of user role and their different capabilities. Whether you have lots of Subscribers or Author, there are ways to display all of them in a list based on their role. So, lets get started.
First of all, lets take a look at the snippet.
<?php
function users_list() {
$users = get_users( array('role' => 'Author') );
if ( !empty( $users ) ) {
foreach ( $users as $user ) {
echo get_avatar($user->ID);
echo '<span>'.$user->display_name.'</span>';
$bio = get_user_meta($user->ID, 'description', true);
echo '<p>Bio: '.$bio.'</p>'; }
} else { echo 'No users found.'; } }
?>
Let me explain it to you. What is happening over here is, on the very first line we declared the function name as “users_list” and then we assigned a variable ($users) to hold the “get_users()” function with parameter/s within the array (most interesting part).
On third line, we checked if the results of our $users variable is empty or not. If it is NOT empty it will perform “foreach” loop and display the Avatar, Display name and Description meta value of the user. If the $users variable returns no value it will simply display “No users found” message.
Simply copy the code above and paste it on your theme’s functions.php file. Once you are done with that simply call the function anywhere you like.
<?php
if (function_exists('users_list')) { users_list(); }
?>
Now, if you place the line mentioned above, it should display the list of users of your site.
Get Creative
There are so many ways, you can get more creative with this snippet and do much more. One of the most important part of this snippet is the parameters/arguments inside the array. This is where you decide (most of the part) what exactly you want to from this function.
I used “role” key and assigned the value of this key as “Subscriber” (user role in WordPress). You can use “Author” to display list of authors of your site or even “Administrator” to display the list of administrators. There are so many different parameters that you can use within this array and get your desired result. How you want to play around with this that’s entirely up to you.
Comment
Leave a Reply