wp_query random post

Doing this in PHP is an awful idea:

  • This page is impossible to cache
  • ordering by random is extremely expensive to query, involving creating temporary database tables, and scans, as it has to copy the entire posts table, then randomly re-order the posts, then finally do the actual query on the new table before destroying it
  • This opens you up to resource exhaustion attacks

For example, this command will ping your random post URL repeatedly. Ran enough times on enough computers, it will bring down your database:

for i in `seq 1 20000`; do curl http://mywebsite.com/postname; done

If you’re on a cheap shared host, it may be enough to call your URL in several browser tabs at the same time to trigger problems.

Not to mention that your redirect sends out HTTP headers, but the code outputs tags beforehand, so headers have already been sent, breaking things and triggering PHP warnings.

The Super Fast Easy Alternative

So instead, do a normal query ordered by data, and output the data as JSON. Then in javascript on the browser, randomly pick one of those posts and do a client side redirect.

This way the page can be cached, your database is protected, and the browser does all the heavy lifting. The database query will be very fast in comparison

Now your problem is as simple as outputting a bit of data in a list, randomly picking something from the list in JS, then using window.location= ... to redirect. No WP knowledge necessary