How to display a random WordPress post inside a page

Here is a handy snippet that displays a random post, so each time a user refreshes the page a different post will appear.

The snippet should be saved as a PHP template for pages and a page has to use it.

Step 1. Create a new file random.php inside your active theme folder and put the following code inside it:

<?php
  /* 
  Template Name: random 
  */ 
?>

<?php $rand_post=get_posts('numberposts=1&orderby=rand'); foreach($rand_post as $post) : ?>

<script> location="<?php the_permalink(); ?>";</script>

<?php endforeach; ?>


Step 2. Login to the WordPress dashboard, select the page on which you want to display random posts, and select the “random” template for it.

Was this post helpful?

Leave a Reply