How to Create a Page that Displays Random Posts

How to Create a Page that Displays Random Posts

Have you ever been to a site and saw this cool feature? They have a link in their top navigation to something like Stumbe! or Read Random Articles, or some other creative text. When you click on that link, it takes you to a page that displays one random page. Each time you refresh, you are delivered with a new post. Well this trick is just for you then.

You would need to follow the trick #1 in this article to create a custom page template. And simply paste this code in there:

01 <?php
02 query_posts(array('orderby' => 'rand', 'showposts' => 1));
03 if (have_posts()) :
04 while (have_posts()) : the_post(); ?>
05
06 <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
07
08 <?php the_content(); ?>
09
10 <?php endwhile;
11 endif; ?>

This is a simple WordPress Loop that is running a query to display random posts and the number 1 in there is telling WordPress to only show 1 post. You can change that number, but most of the time people do it one post a time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: