How To Get Random Posts From WP Query

Yesterday I received a email asking about the images that are above the main content area. Tim wanted to know “how I get them to show up in random order”. The way that I did it is using custom WP Query so you need to be using WordPress. I am using one of my categories witch is Photography and I’m calling them in a random order. I you interested in seeing how this is done then keep reading.

Random Posts From WP Query

In my header above the main content area I wanted to show off some images from my Photography category in a random order. Show I added this code to get the job done.

<?php $my_query = new WP_Query('cat=8&showposts=3&orderby=rand');
while ($my_query->have_posts()) : $my_query->the_post();
$do_not_duplicate = $post->ID; ?>
<?php endwhile; ?>

So the key to getting this to work is: cat=8&showposts=3&orderby=rand

Cat=8 is my Photography category. You can also use category_name=photography.

If you want to show more than one category then you will add more category numbers like so.
Cat=8,12,1 and so on.

showposts=3 is the number of posts you want to show.

orderby=rand is the random order.

You also can use: orderby=
author, date, category, id, title, modified, parent and rand.

Nothing new here but works good for what I need. Hope that help ya Tim.

5 Replies to “How To Get Random Posts From WP Query”

  1. Thank you very much for your advice!

    It really worked out for me as I implemented a “Did you read?”-feature into my template.


Comments are closed.