How To Show Random Posts In WordPress Theme

I’ve a blog on which I display photos from a single category on home page. However if photos are not added on regular basis then the blog becomes boring. So I had to find a way to show random posts from the category. And this has to be done in WordPress theme.

By default the WordPress shows posts by date. The solution is to query posts and sort them randomly.

[sourcecode]
<?php query_posts(array(‘cat’ => 986, ‘showposts’ => 9, ‘orderby’ => ‘rand’));
if (have_posts()) : while (have_posts()) : the_post()

// do your stuff

<?php endwhile; ?>
<?php endif; ?>
[/sourcecode]

The above code is to show 9 random posts from the category 986. If you intend to use above code then replace the category id with whatever category you want to show the posts from.

If you have WP Super Cache or other plugin installed then probably you will not see randomness. So if you want to test it’s working then open website in different browsers and see the result.