Show two random posts from custom post type

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="https://wordpress.stackexchange.com/questions/109623/[using custom meta to get link address here]"><img src="[using custom meta to show image here]"></a></div>';
$counter++;
endwhile; ?>

1 Answer
1

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.

Leave a Comment