1

I'm looking to display a single featured post from my latest 3 posts at random. I've managed to get it up and running picking any post at random just fine, but I want to filter it down to only the latest 3.

<?php

$args = array(
    'post_type' => 'post',
    'orderby' => 'rand',
    'posts_per_page' => 1,
    'post_status'   => 'publish'
    );

$rand_query = new WP_Query( $args );

if ( $rand_query->have_posts() ) :
    while ( $rand_query->have_posts() ) : $rand_query->the_post();
?> 

// DIV FOR SINGLE FEATURED POST HERE // etc... 

Obviously, if I change the posts_per_page to 3 I then get 3 divs containing featured post previews. I only want the one post that is picked at random from those last 3. A date query won't work as the posts aren't regular.

5
  • 2
    you can use "posts_per_page = 3" to retrieve the last 3 posts and then use secure.php.net/array_rand to select 1 of these 3.
    – mmm
    Jul 13, 2018 at 10:48
  • Note that ordering by rand is extremely expensive, it's one of the slowest things you can do in WP_Query, you don't want to make the DB do the random bit
    – Tom J Nowell
    Jul 13, 2018 at 10:59
  • @mmm please write your answer as an answer not a comment
    – Tom J Nowell
    Jul 13, 2018 at 11:01
  • @TomJNowell Any tips on avoiding ordering by rand? Does Krzysiek's answer below using shuffle avoid this issue?
    – adamdanw
    Jul 13, 2018 at 11:13
  • Yes because he does the shuffling in PHP, not in the DB query
    – Tom J Nowell
    Jul 13, 2018 at 11:16

1 Answer 1

5

Here's my approach...

First you have to select 3 latest posts, then you have to pick random one of them...

But it's easier to shuffle selected posts than picking only one of them - that way you can still use normal loop:

<?php
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'post_status'   => 'publish'
    );    
    $rand_query = new WP_Query( $args );

    shuffle( $rand_query->posts );

    if ( $rand_query->have_posts() ) :
        while ( $rand_query->have_posts() ) : $rand_query->the_post();
?>

    // HERE GOES THE DIV WITH POST

<?php
            break;  // we want only one post to be shown, so we break the loop
        endwhile;
    endif;
?> 
2
  • This was a very quick fix and solved my problem immediately - I wasn't aware of the shuffle function.
    – adamdanw
    Jul 13, 2018 at 11:11
  • @adamdanw simplest solutions are the best :) Jul 13, 2018 at 11:12

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.