Wordpress Logo

Randomising the order of posts in WordPress

Posted by

Just before ‘the loop‘ of a WordPress site, you would normally use query_posts(). Not only does this set a global variable somewhere deep inside the WordPress core to an array of posts but it also returns a referenceWikipedia: In computer programming, a reference is a value that enables a program to indirectly access a particular datum, such as a variable's value or a record, in the computer's memory or in some other storag... to that array. This is pretty useful if you want to manipulate it before ‘the loop’. A good example of this is randomising the array, like I have with the last 3 posts on the home page of this site.

You can do this by simply wrapping the query_posts() call in a shuffle:

<?php
shuffle(query_posts()); // query_posts() will probably have some parameters passed to it. That's ok.
?>
Or you can assign the return of query_posts() by reference and shuffle that:
<?php
$posts =& query_posts();  // query_posts() will probably have some parameters passed to it. That's ok.
shuffle($posts);
?>

 

Leave a Reply

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