RiteTurnOnly.com

blogging for people... not machines

Displaying Random Post

8 November 2008 under WordPress

Back in April I showed you how to add a custom loop to your sidebar for displaying the latest posts from a given category using the query_posts function. (see Custom Loop in Sidebar) Here’s a little variation that will display a random post on a page using that very same query_posts function. Why do this? It’s a great way to showcase posts that have long since been banished to the archives and might not otherwise be seen.

First, we need to create a new Page template. You can easily build one using your theme’s own page.php as an example. For the sake of simplicity let’s call it random.php. Upload the new file to your theme’s folder. Next, from the “write page” screen write your new page and select the new Page template from the menu. (click image below to enlarge)

You can use whatever title you want for the page but to keep things simple I’m going to use Random. You needn’t add anything to the content - just add the title. Once you publish it you will have a blank page - that’s fine.

Now for the magic. Open up random.php and look for the loop. It will look something like this …

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

…and we modify it using the query_posts function so that it now looks like this…

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

All you need to do is change SomeCategoryName to the actual category name you want to pull the posts from. Showposts can also be changed from 1 to whatever you like if you want to display more than one post. However one is enough I think. You can see it in action on this very blog by clicking Random in the header navigation.

Further reading:
http://codex.wordpress.org/The_Loop
http://codex.wordpress.org/Template_Tags/query_posts
http://codex.wordpress.org/Pages#Page_Templates

Comments

Leave a Reply