Take the 2-minute tour ×
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?

<?php
$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>';
$counter++;
endwhile; ?>
share|improve this question

1 Answer 1

up vote 1 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

Your Answer

 
discard

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.