How To Get Random Posts From WP Query

Added: June 15th, 2009
Filed under: Featured
Comments 0
Add your comment!
Tags:

About This:

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; ?>
<!--CUSTOM LOOP STUFF HERE -->
<?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.


Twitter Facebook MySpace Digg Stumble It!

Leave a Reply