Paulund
2012-10-03 #wordpress

Create A Random Post Custom Page

In a previous tutorial you would of learnt how you can create custom page templates to add additional functionality to your theme. Some of the example pages mentioned were:

  • Contact Us page, with validation.
  • Full width content page
  • An Archives page

Here we are going to look into how we can create a page template which will display a random post from your blog. This is a good technique used to get your visitors to view your older content. If readers are new to your blog this will be a good page to send them so they can see a mix of your posts.

Creating A Page Template

First we need to create a page template, this is done by adding a new file to your theme and place the following at the top.

<?php
/*
Template Name: Random Post
*/
?>

Having these comments at the top of the file means that Wordpress will see this as a page template, now you can see this in the template drop down when creating new pages. To display post on the page we normally need to use the basic loop functionality.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
					
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
	<h1 class="entry-title"><?php the_title(); ?></h1>
						
	<div class="entry-content">
             <?php the_content(); ?>
        </div>
</div>
	
<?php endwhile; endif; ?>

But we want to get a random post so we need to change the query used to get posts to get a random post, this is done by using the function query_post() and passing in parameters orderby and showposts. Orderby parameters will define how the posts returned are ordered and the showposts will define how many posts are returned. query_posts(array('orderby' => 'rand', 'showposts' => 1));

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
					
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
	<h1 class="entry-title"><?php the_title(); ?></h1>
						
	<div class="entry-content">
             <?php the_content(); ?>
        </div>
</div>
	
<?php endwhile; endif; ?>

The above code is all you need to display the random so you can place this inside the page template.

Full Random Post Page Template

<?php
/*
Template Name: Random Post
*/
get_header(); ?>

<section>
  	<div class="inner">
                
	<?php 
		query_posts(array('orderby' => 'rand', 'showposts' => 1));

		if (have_posts()) : while (have_posts()) : the_post(); ?>
					
		<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
                    
		<h1 class="entry-title"><?php the_title(); ?></h1>
						
			<div class="entry-content">
                            <?php the_content(); ?>
			</div>

		</div>
	
		<?php endwhile; endif; ?>
	</div>
</section>
    
<?php get_sidebar(); ?>

<?php get_footer(); ?>

Now just create a page using this template and each time you go to this page you will see a different post.