Skip to content

How To Display Random Registered Users In WordPress

Yesterday, I shared a snippet to show recently registered users on your multi-user WordPress website. Here’s another snippet which will show random registered users in your WordPress website’s front-end. It’s also a great to get more users to join your site.

This snippet comes from the WPBeginner. Just add following snippet to your current theme’s functions.php file:

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');

2 thoughts on “How To Display Random Registered Users In WordPress”

  1. Thank you for this. It helps me in my quest to have a fun idea for my site.
    I would like to have a randomly featured member for one week in a wordpress page. This script will select the random user, but how do I keep the same user for one week, before the new random user is selected ? Thanks in advance.

    1. Matthew Knight (@webponce)

      You would need to use a ‘seed’ in the RAND() call, for instance, each time you call RAND(1), it will return the same random ordering, and then use RAND(2) as another random ordering. If you want to keep the same user each week, generate a unique week string, perhaps made up of the year and the week number, i.e. the second week of the 2015 would be 201502. You can then pass this in to the RAND() method.

      $weekstring = date(‘YW’);
      $query = “SELECT user_nicename, user_url, user_email FROM $wpdb->users ORDER BY RAND($weekstring) LIMIT 5”;
      $usernames = $wpdb->get_results( $query );

Leave a Reply

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