I’m trying to display a list of 5 authors randomly. Here are some solutions I had found:
https://stackoverflow.com/questions/5502609/get-authors-randomly
https://wordpress.stackexchange.com/a/91326/1044
I’m currently using the former solution except that I use WP_User_Query
like so:
$args = array(
'role' => 'subscriber'
);
$wp_user_query = new WP_User_Query($args);
$authors = $wp_user_query->get_results();
// Shuffle list to get random results
shuffle($authors);
However, to my amateurish understanding, this will fetch the whole list of users. So I’m just wondering if I had around 2000-5000 users (or more), will this affect page load drastically? how can I make this more efficient?
UPDATE:
Also would array_rand()
be a more efficient method compare to shuffle()
?
If you are concerned about efficiency, you might want to use the Transients API to store the query. Storing something that you want to randomize might seem counter-intuitive, but if you store the entire query, you can always randomize and manipulate the resulting array to get the results you want.
Here’s how to get all the subscribers and store them in a transient, with a but of straight PHP at the end to shuffle/randomize the result and then pick off the first 5 results using
array_slice()
and then to make sure the transient is up to date, we’ll delete it when a user is updated or added:
You don’t want to fetch all users if you only need
5
.If you want to use
WP_User_Query()
to fetch 5 users by random, you can try to use thepre_user_query
hook to overwrite the orderby part:where
Update:
This article contains a trick to cut down the number of rows, using a special
WHERE
condition, before theORDER BY RAND()
kicks in … as far as I understand it.The
WHERE
condition in your case might beSo if you have a very large number of users, then you could try out this modified action callback:
if the trick from the above article is working!
Here is a more general version of the modified callback: