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 Answers
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.

Leave a Reply

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