wp-content ยป themes ยป functions.php ยป How to display a Random ๐Ÿ”€ WordPress Post inside a Page

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.

See also  How to Automatically Create Post Tags from Post Title

Was this post helpful?

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended