Display random posts in WordPress

Learn how to display random posts in WordPressOn a blog, it’s typically only a small portion of the posts that’s being read.

However if you want to inspire your readers to read further posts, a random post script can be a effective tool to expose additional content to your users and thereby increase the stickiness of your site.

In this post you’ll learn how easy it is to insert a random post script in WordPress.

Random post script

Inserting a random post script is easy in WordPress. WordPress has strong standard functions that can easily be modified to select random posts from your content.

The PHP snippet:

query_posts(array(‘orderby’ => ‘rand’, ‘showposts’ => 1));

Selects 1 random post from the WordPress database.

The snippet can be included in a small php script the following way:

<?php
 query_posts(array('orderby' => 'rand', 'showposts' => 1));
 if (have_posts()) :
 while (have_posts()) : the_post(); ?>

<h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>

<?php the_content(); ?>

<?php endwhile;
 endif; ?>

Next step is to included this functionality in your blog. This can easily be done by finding the relevant page template in the WordPress backend. If you want to display link to a random post in the single post page you should navigate to this page:

Apperence -> Editor -> single.php

And paste the script where ever you like the random post link to be displayed.

Conclusion

A link to random posts can increase the stickiness by inspiring your readers to view additional content on your blog. The script is very easy to implement, and can be styled in many ways to fit perfectly into your blog.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

One Reply to Display random posts in WordPress

  1. Nadeem Khan says:

    Is there any way of doing this :

    a button or an image which when pressed could display a random post ?

Comments are now closed for this article.