WordPress – Display Random Posts

So you want to display a random list of posts, maybe in a sidebar widget…

One way to do it is to use the query_posts() function

<?php 
    query_posts('showposts=6&amp;amp;orderby=rand'); 

    if (have_posts(){
	while (have_posts()){
	the_post();

	//do something with the postdata
	}
}
?>

But it’s easy to get in a mess with query_posts – as they do say…

The query_posts function overrides and replaces the main query for the page. To save your sanity, do not use it for any other purpose.

Often best to instantiate a new, completely separate object where you can see it, as it were:

	$args = array('showposts'=>6, 'orderby'=>'rand');
	$customQuery = new WP_Query($args);

	if($customQuery->have_posts()){
		while ($customQuery->have_posts()){
			$customQuery->the_post();
	//do something with the postdata
 }

}

It’s a good general rule to get into the practice of using WP_Query in cases like these – a lot safer…