Improving WP_Query for performance when random posts are ordered

I have made a new query after I’ve asked a question about my query_posts code… you guys didn’t find that great, so I decided to change that.

I made this:

$page = (get_query_var('paged')) ? get_query_var('paged') : 1; 
$rand = new WP_Query("showposts=10&orderby=rand&paged=$page"); 
while($rand->have_posts()) : $rand->the_post();

My question is: how can I improve this?

Isn’t it better to use an array? So the same code, with an array or not?

So like this:

$rand = new WP_Query( array(
    'showposts' => '10',
    'orderby' => rand
) );

Would this make my performance better?

And I read something about adding:

'update_post_meta_cache' => false

To improve the performance if terms are not going to be used. My question: what are terms anyway? Are they trying to say tags and / or categories with this?


function random_posts( $query ) {
    if ( $query->is_home() && !$query->is_paged() && $query->is_main_query() ) {
        $query->set( 'orderby', 'rand' );

What if I would use this? Do I have to change my WP_Query or do I have to remove it? I don’t get what pre_get_posts does actually.

Solutions Collecting From Web of "Improving WP_Query for performance when random posts are ordered"

The problem with orderby rand is that on most setups the database will load all posts into memory, then randomly order them, and return what you asked for. It’s that loading into memory that makes the query super slow/expensive

Also yes, terms are individual categories and tags, where category is a taxonomy, and the ‘development’ category is a term in that taxonomy.

Finally, your initial code snippet implies you’re using a page template or attempting to override what’s shown on the page. This is bad as it discards the main query and launches a second query. The cost of the first query still occurs, but it’s discarded so it’s a waste of time. This is why query_posts is considered harmful, replacing it with a custom WP_Query loop doesn’t fix that. Consider using pre_get_posts instead to intercept the main query and change it