Display a Random Post (with AJAX Refresh)

Hostnbit

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.

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 sidebar.php.

<h4>Random Post</h4>
<ul>
	<li id="randomPost">... loading ...</li>
</ul>
<a href="#" id="another">Get another!</a>

2. Create a new Page template

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

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

<?php 
    query_posts('showposts=1&orderby=rand'); 
    the_post();
?>

<a href='<?php the_permalink(); ?>'><?php the_title(); ?></a>

3. Publish a Page using this template

Could be anywhere you want. On this blog it’s at /random/.

4. The jQuery

You’ll need jQuery loaded and a link to your own custom script going, then add this:

$("#randomPost").load("/random/");
$("#another").click(function(){
   $("#randomPost")
            .text("... loading ...")
            .load("/random/");
   return false;
});

 

UPDATE

The above doesn’t work as written in Internet Explorer, which likes to cache AJAX requests. To fight this, just append a random URL parameter to the end of the load URL. Like so:

$("#another").click(function(){
   $("#randomPost")
            .text("... loading ...")
            .load("/random/?cachebuster=" + Math.floor(Math.random()*10001));
   return false;
});

Thanks to Andy for this fix, who is using it on this web app.

Hostnbit

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Menu Title
Scroll to Top