How to: create a page to display a random post

Your blog have probably a lot of posts that your readers haven’t read yet. Why not creating a page and display a random post on it? Here’s an easy way to do it.

The first thing to do is, of course, to create a page template.
Once done, paste the following code in your new page template:

<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
     while (have_posts()) : the_post(); ?>
         // WordPress loop, your random post will appear here
     endwhile;
endif; ?>

That's it! Wonderful way to give a second life to old posts, isn't it?

14 Responses

Oct 19 2008 11:26

I am using plugin that creates “random” link. Click link – get redirected to random post. URL, comments and everything in place.

Oct 19 2008 11:35

I heard about this plugin before, what was the name?

Oct 19 2008 12:31

Random redirect
http://wordpress.org/extend/plugins/random-redirect/

By the way about comments/posts question that I submitted. I had found recently released plugin that does exactly that so you can skip my question. :)
http://wordpress.org/extend/plugins/most-comments/

Oct 19 2008 13:03

Thanks for the info! No problem about your question, though I have the answer, which will be published soon. So even if you use a plugin you’ll still be ableto understand how it works :)

Oct 19 2008 15:19

Hey Jean

So I presume this resourceful blog is an extension of Cats Who Code, is it not? Very nice and well laid-out.

Yan

Oct 19 2008 15:32

Hello Yan, glad to see you on here! Well WpRecipes isn’t really a Cats Who Code “extension”, it is more a place where i’ll share usefull WordPress recipes that doesn’t fit Cats Who Code editorial line.

Oct 19 2008 15:35

Awesome and I’m loving the idea of having a one-stop place for all thing WordPress…

Good luck, buddy..

Yan

Oct 22 2008 08:53

Thanks for the tip…

Nov 09 2008 15:37

It’s run perfectly ! thank you so much !

Nov 09 2008 17:43

You’re welcome :)

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required