Displaying a random user with a shortcode

By default WordPress allow only order ASC and DESC. However, you can use WP_User_Query and the action pre_user_query to adjust the query (that is passed by reference) just like you want.

This is efficient because you get only one user, not all.

function my_user_by_rand( $ua ) {
  // remove the action to run only once
  remove_action('pre_user_query', 'my_user_rand');
  // adjust the query to use random order
  $ua->query_orderby = str_replace( 'user_login ASC', 'RAND()', $ua->query_orderby );
}

function display_random_user(){
  // add the filter
  add_action('pre_user_query', 'my_user_by_rand');
  // setup the query
  $args = array(
    'orderby' => 'user_login', 'order' => 'ASC', 'number' => 1
  );
  $user_query = new WP_User_Query( $args );
  // run the query
  $user_query->query();
  // get the result
  $random = ! empty($user_query->results) ? array_pop($user_query->results) : FALSE;
  // just for debug
  print_r($random);
}

Leave a Comment