Display 5 random posts in Wordpress
Scribbled on Tuesday, August 12th, 2008Using plugins for every litte thing in Wordpress is a really bad idea. At least I like to have my own solution before anyone else’s. So I read wordpress function reference and database schema. At first it seemed so easy that I thought why would anyone make a plugin for this. Here is the first code that is itself given in Wordpress site to display random posts.
Solution 1 (Failed for me):
[sourcecode language='php']
$rand_posts = get_posts('numberposts=5&orderby=rand');
foreach( $rand_posts as $post ) :
?>
[sourcecode language='css']
have_posts()) : $recent->the_post(); ?>
[sourcecode language='css']
$querystr = "SELECT * FROM (SELECT wposts.* FROM $wpdb->posts wposts WHERE wposts.post_status = ‘publish’ ORDER BY rand()) as y limit 5 “;
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
is a nested subquery where the query inside the brackets retrieves the posts that are published (it includes published pages too) and then order it by random. This randomly ordered list is then used to retrieve 5 first posts.
See the result at the bottom of this website ;p
Though I haven’t tested the performance but it works fine here.

No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.





5 Responses to “Display 5 random posts in Wordpress”
Cool man!! i was thinking of such a tool in the morning, wondering where i can get it! thnx…
By Su on Tue 12th Aug, 2008
Whoooooooosh!
Didn’t understand a word! hehehe…
Right over my head!
By Nikhil on Wed 13th Aug, 2008
@Su
But can u really edit the php files. I think your wordpress blog is free and it doesn’t allow editing files etc.
@Nikhil
Don’t worry, anytime you need help just mail me.
By T on Wed 13th Aug, 2008
@T : i tried it out and it didnt work… i’m not into programming and so couldn’t figure out the problem…
By Su on Sat 16th Aug, 2008
@Su
But I suppose you are using Free Wordpress Blog and it doesn’t allow you to save the changes made in code or CSS.
By T on Sat 16th Aug, 2008