How to Display a Random Post with the help of AJAX

In this post we will show you how you can create a page that displays a random post in WordPress, So you have a blog, and are pretty regular in posting on it. However sometimes the situation arises that you are on a brief sabbatical,and will not be posting for sometime ; so you would want your past works to do the job for you and keep your readers entertained.

I think you’ll be surprised at how ridiculously easy this is. We are going to leverage some serious smartness from both WordPress and from the JavaScript library jQuery.

You can do this by including an option for generating Random Post in your sidebar or anywere in your blog noticed mine just above the footer. Here are the steps to do so:

1. Set up area for Random Post (HTML)

This could be anything really, just so long as it is a text page element with an ID you can target. I put this in our footer.php file, if you want to include this in your sidebar than include this code in your sidebar.php file.

<div class="row" id="random">
  	<div class="sec-head col g12">
    	<h4>Random Posts</h4>
    	<a class="load" id="another" href="#">LOAD MORE</a> 
    </div>
    <div id="randomPost">
    
    </div>
</div>

2. Create a new Page template

The sole purpose for this page template is to query the posts and display the random post. Look how easy it is.

<?php
/*
Template Name: Random Post
*/
?>
<?php 
    query_posts('showposts=1&orderby=rand'); 
    the_post();
	$args = array( 'numberposts' => 4, 'orderby' => 'rand' );
	$rand_posts = get_posts( $args );
?>
<?php
	foreach( $rand_posts as $post ) :  setup_postdata($post);
?>

<div class="random-post col g3">
  <a class="dt-thumb" href="<?php the_permalink(); ?>">
  <?php if(has_post_thumbnail( $post->ID )) :
		  $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'post-thumbnail' );
	    ?>
  <img src="<?php bloginfo("template_directory"); ?>/timthumb.php?src=<?php echo $image[0]; ?>&w=225&h=225&zc=1" border="0" />
  <?php endif; ?>
  </a>
  <div class="post-info">
    <h3 class="entry-title"> <a href="<?php the_permalink(); ?>">
      <?php the_title(); ?>
      <span class="rarr hide">&nbsp;&nbsp;?</span> </a> </h3>
    <div class="cat-links"> <span class="entry-meta-prep">Posted in </span>
      <?php the_category(', ') ?>
    </div>
  </div>
</div>
<?php endforeach; ?>

3. Publish a Page using this template

Now it’s time to publish a page that display your Random Post on your wordpress blog. For this tutorial it’s at /random/.

4. The jQuery

  <script type="text/javascript"> 
	$(document).ready(function(){
							   
		loadPostsFun = function(){
			$.ajax({
				url: "/random/",
				beforeSend : function(){
					//$(".random-post").html("");
					$(".random-post").append("<div class='load-overlay'></div>");
				},
				success: function(response){
					$("#randomPost").html( response );
				}
			});	
		};
		
		
		
		$("#another").click(function(){
			loadPostsFun();	
			return false;
		});
		
		loadPostsFun();	
		
	});
  </script>

5. CSS

#random {
	background: #545454;
	border-top: 7px solid #777;
	border-bottom: 7px solid #444;
	padding: 20px 10px 20px;
}
#random .sec-head {
	margin: 0 10px 20px;
	background: none;
}
#random .sec-head h4 {
	color: #ccc;
	background: none;
	text-shadow: 0 1px 1px #333;
	font-family: 'Yanone Kaffeesatz',arial,serif;
}
#random .sec-head a.load {
	float: right;
	text-decoration:none;
	padding: 0 10px 0 33px;
	font-size: 14px;
	font-family:'Yanone Kaffeesatz',arial,serif;
	color: #ccc;
	line-height: 24px;
	background: #666 url(images/reload.png) 10px 0 no-repeat;
	-moz-border-radius: 20px;
	-webkit-border-radius: 20px;
	border-radius: 2px;
	-moz-box-shadow: 0 0 2px #222;
	-webkit-box-shadow: 0 0 2px #222;
	box-shadow: 0 0 2px #222;
}
#random .sec-head a.load:hover {
	text-decoration: none;
	background-color: #777;
}
#random .random-post {
	height: 225px;
	overflow: hidden;
	-moz-box-shadow: 0 0 2px #222;
	-webkit-box-shadow: 0 0 2px #222;
	box-shadow: 0 0 2px #222;
	position:relative;
}
#random .random-post .dt-post-image {
	margin: 0;
	display: block;
}
#random .random-post .post-info {
	float: left;
	position: absolute;
	color: #aaa;
	text-shadow: 0 1px 0 #000;
	margin-top: -228px;
	padding: 15px;
	width: 200px;
	background: url(images/black80pct.png);
}
#random .random-post .post-info .cat-links, #random .random-post .post-info p {
	display: none;
}
#random .random-post .post-info:hover .cat-links, #random .random-post .post-info:hover p {
	display: block;
}
#random .random-post .post-info:hover h3 .rarr {
	display: inline;
}
#random .random-post .post-info h3 {
	line-height: 1.2;
	margin: 0;
	font-size: 16px;
	letter-spacing: 0;
	background:none;
	padding:0px;
}
.sec-head h4 {
	background-color: #FFFFFF;
	display: inline-block;
	font-size: 24px;
	line-height: 24px;
	margin: 0;
	padding: 0 20px 0 0;
}
#random .random-post .post-info h3 a {
	color: #ddd;
	display: block;
	font-family: 'Cuprum', sans-serif;
	text-decoration:none;
}
#random .random-post .post-info h3 a:hover {
	color: #fff;
	text-shadow: 0 1px 2px #000;
}
#random .random-post .post-info .cat-links {
	color: #777;
	margin: 5px 0 10px;
	font-size: 10px;
}
#random .random-post .post-info .cat-links a {
	color: #999;
}
#random .random-post .post-info p {
	padding-bottom: 5px;
	font:11px Arial, Helvetica, sans-serif;
}
.load-overlay {
	width: 225px;
	height: 225px;
	top: 0px;
	position: absolute;
	background: #000 url(images/ajax-loader.gif) center center no-repeat;
	opacity: .5;
	filter: alpha(opacity=50);
	z-index: 100;
}

6. Rejoice

I told you it would be easy! Check out our Random Post section just above the footer for a live example.

How to Display a Random Post with the help of AJAX

Join Our Email Newsletter

Like what you read here in this blog post? Get free blog updates in your Email!

When signing up you will initially receive a confirmation email requiring your approval to complete the Subscribtion.

Up to 90% off over 6,000 courses!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>