2

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; ?>
7

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.

  • Is this 'computationally' expensive if you have several thousands of posts? I mean the random ordering. – Drunken Master Jun 22 '15 at 7:47
  • 1
    @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 '15 at 13:35
  • I made a plugin using this code: wordpress.org/plugins/load-random-post – Shiva Pareek Feb 25 '18 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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