1

In the footer.php I show all the authors of my blog with the following code:

$args = array(
    'meta_key' => 'last_name',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query( $args );
$wp_user_query->query_orderby = str_replace( 'user_login', 
    'wp_usermeta.meta_value', $wp_user_query->query_orderby );

// Get the results
$authors = $wp_user_query->get_results();

Is it possible to limit the output to 5 random users? Like posts_per_page => 3 and orderby => rand?

2

Yes possible, just tell WordPress to use RAND() SQL sorting when passing rand in orderby parameter:

add_action( "pre_user_query", function( $query ) {
    if( "rand" == $query->query_vars["orderby"] ) {
        $query->query_orderby = str_replace( "user_login", "RAND()", $query->query_orderby );
    }
});

Now you can use:

$users = get_users( array(
    'meta_key' => 'last_name',
    'orderby' => 'rand',
    'number'  => 3 // limit
));

print_r( $users );

Hope that helps.

  • Your solution works perfect thank you! I made a mistake in my post. The output should always be 5 random users, not limited to 5. – Peesen87 Jun 30 '16 at 7:00
  • Thanks but isn't it always outputting 5 random users? – Samuel Elh Jun 30 '16 at 19:10
  • No the output is something between 1 and 5 users – Peesen87 Jul 4 '16 at 8:58
0
function get_random_authors($number) {

$users = wp_list_authors( array(
'orderby' => 'rand',
'number'  => $number // limit
));

return $users;

}

print_r(get_random_authors(3));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.