If you’re a developer, then there have been times you beat your head against a wall trying to figure out why something that worked in local development doesn’t work on a live server. So you troubleshoot…
- Is the WordPress version the same?
- Is the PHP version the same?
- Is the database version the same?
Yes, yes, and yes. So then you turn on DEBUG mode or install the Query Monitor plugin and compare more notes between local and live.
And you scratch your head in confusion when everything looks identical.
Next up, you turn to Google which takes you to Stack Overflow where some kind soul discovered the answer to your problem and posted the solution back in 2017. God bless.
So let’s get to the answer that brought you to this post.
‘ORDERBY’ => ‘rand’ isn’t behaving
You’ve got a custom query. You want to order the results randomly. So you use something like:
'post_type' => 'your-cpt', 'posts_per_page' => '-1', 'orderby' => 'rand',
And it works just like you’d expect it to work (in your local dev environment). But you push to the live server and… it’s not random, so you go through the steps mentioned earlier.
That’s when you stumble across the issue: WP Engine disables random ordering by default. This is understandable because ordering randomly can be an expensive query on a big database.
But if you’ve done your homework and understand the risks and have tested the performance of your solution vs other alternatives for random results (like
shuffle()), WP Engine gives you a crazy simple way to enable random order.
Enable ORDERBY RAND() on WP Engine
From your /wp-admin, click on the WP Engine menu item. Under “Advanced Configuration” you’ll see an option to “Allow ORDER BY RAND( )”. It’s disabled (by default). Select “Enabled”, save your changes, and you’re golden.
Go refresh the page where that troublesome query was and watch in delight as it runs just like it did in development.
Extra bonus alert
If you landed on this post, chances are you (or your client) are hosting with WP Engine. If you’re using WP Engine and enjoy the platform, you can make some decent dough as an affiliate.
Sign up for the WP Engine affiliate program here and earn as much as $200 per referral. And tell ’em Carrie Dils sent ya.