When we need to pull a random post from the database, most obvious solution is to use WP_Query and set order to ‘rand’.
This works fine on smaller databases, but unfortunately with large number of posts in the WordPress, using random order is not the most efficient way and creates some unnecessary load on the database. Some hosting providers (e.g. WPEngine) actually disabled random order as a bad practice.
There is a simple workaround which lets you to get random post without sacrificing performance:
- run WP_Query and get posts count
- generate random number between 1 and number of posts count
- Run WP_Query again with 1 post per page setting and get the page number using random number generated
Here is actual code you can put into your widget or page template: