Sign up ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I've set the code below to show info from the latest two posts of a custom post type (it also loops through and adds a class of first to alternate items for layout purposes). How would I amend this to show two random posts?

$counter = 1;
$args = array( 'post_type' => 'custom_advert', 'posts_per_page' => 2 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="sixcol ';
if ( $counter % 2 == 1 ) { echo 'first'; }
echo '"><a href="[using custom meta to get link address here]"><img src="[using custom meta to show image here]"></a></div>';
endwhile; ?>
share|improve this question

1 Answer 1

up vote 2 down vote accepted

You need an orderby argument.

$args = array( 
  'post_type' => 'custom_advert', 
  'posts_per_page' => 2,
  'orderby' => 'rand'

That should pull posts in a random order and stop after retrieving the first two, hence two random posts.

share|improve this answer
Amazing, thankyou. – jasonbradberry Aug 12 '13 at 9:27
Is this 'computationally' expensive if you have several thousands of posts? I mean the random ordering. – Drunken Master Jun 22 at 7:47
@DrunkenMaster : WordPress uses MySQL's RAND() for this and that is never really an efficient operator, but if that is what you need, that is what you need. There are some rather complex attempts at a "better" RAND if you search around but I have never seen the benefit. – s_ha_dum Jun 22 at 13:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.