How to Randomly Display Registered Users in WordPress

67

Your users are the superstars of your multi-user WordPress site. There are many ways you can highlight users and authors on your site. Previously we showed you how to add an author info box, and how to display recently registered users. In this article, we will show you how to display a random list of registered users in WordPress.

Displaying registered users randomly in WordPress

First thing you need to do is copy and paste the following code in your theme’s functions.php file or in a site-specific plugin.

    function wpb_random_users() {     global $wpdb;    $randomusers = '<ul class="random-users">';    // Query database for users  $usernames = $wpdb->get_results("SELECT user_nicename, user_url, user_email FROM $wpdb->users ORDER BY RAND() LIMIT 5");    // Display users in a list  foreach ($usernames as $username) {    if (!$username->user_url) :    $randomusers .= '<li>' .get_avatar($username->user_email, 45) .$username->user_nicename."</li>";    else :    $randomusers .= '<li>' .get_avatar($username->user_email, 45).'<a href="'.$username->user_url.'">'.$username->user_nicename."</a></li>";    endif;  }  $randomusers .= '</ul>';    return $randomusers;    }    add_shortcode('randomusers','wpb_random_users');

This code queries the WordPress users table in your database and selects a random row, then it outputs the results in a bulleted list with user’s avatar and name. If a user has provided the website URL in their profile, then it will link the user name to their website.

Next thing you need to do is display the list of registered users. To do this, all you need to do is add the following line of code in your theme file where you want the user list to be displayed (such as sidebar.php, footer.php etc).

  <?php wpb_random_users(); ?>

You can also display a list of random users from your site using this shortcode in a post, page, or a widget.

[randomusers]

We hope this article helped you display a random list of registered users on your WordPress site. If you were looking to display a list of your staff members, then you should check out this tutorial on how to create a staff list in WordPress.

If you have any questions or feedback, then please leave us a comment below. Also don’t forget to follow us on Twitter and join us on Google+