How to display random 10 authors with their avatars?

I am using below code to display all blog author avatars in my wordpress webpage. However, I would like to display 10 random avatars, not all. Is there a way to get by without using any plugin?

$blogusers = get_users_of_blog();
if ($blogusers) {
    foreach ($blogusers as $bloguser) {
        $user = get_userdata($bloguser->user_id);
        echo get_avatar( $user->ID, 70 ); 
    }
}

      

+3


source to share


1 answer


get_users_of_blog

deprecated. Use instead get_users

:

https://codex.wordpress.org/Function_Reference/get_users

Using only get_users

, you cannot get random users, but you can use the action pre_user_query

to update the clause ORDER BY

in SQL:



// Update the query to order by random
function randomize_users(&$query) {
    $query->query_orderby = "ORDER BY RAND()";
}

// Attach the function to the pre_user_query hook
add_action( 'pre_user_query', 'randomize_users' );

// Get the users
$users = get_users(array(
    'blog_id' => get_current_blog_id(),
    'number' => 10
));

// Remove the action so future queries won't be affected
remove_action( 'pre_user_query', 'randomize_users' );

      

Source: https://core.trac.wordpress.org/ticket/20606

+1


source







All Articles