Randomly display posts on a site hosted by WPEngine? [closed]

You’re right, RAND() is a performance killer which almost every time involves a full table scan, and if you have a large number of posts in WordPress, it’s going to be a nightmare.

So instead of displaying random posts, it’s much more efficient to display what only seems like a random post, but in reality is not. Here’s a simple example:

  1. You have the total posts count
  2. Query for 20 posts with an offset of a random number between 1 and ( total – 20 ) obtained in PHP.
  3. Cache the result for an hour or longer.
  4. Use PHP to display one of the 20 posts from cache at random.

This means that you’re going to query the database only once every hour.

The query will be less random and much faster, because you’re not doing RAND() but using OFFSET instead. With WP_Query this can be conveniently combined with max_num_pages, posts_per_page and paged arguments.

And finally, since you’re obtaining 20 posts, the result in step 4 will seem pretty random to visitors that won’t refresh the page more than 20 times in less than an hour.

Also worth noting, that if you’d like to by-pass page caching, you can pass all your 20 posts to JavaScript and pick one at random with JS.