Get random WordPress post displayed without slowing down server

Using native random order works fine on small databases, but kills the load speed when your WordPress has a lot of posts, so here is a better way to pick up a random post from the database.

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:

 

Comments are closed.

Learning WordPress development?

Subscribe and never miss a post about WordPress themes and plugins coding techniques, WordPress website development workflow and best practices.