I know that I can display 4 random posts by doing something like:

get_posts('orderby=rand&numberposts=4');

 

What I’m trying to achieve is starting with a random item, but then showing the next 3 posts that are in chronological order.

I’m thinking something along the lines of this:

$posts = get_posts('orderby=rand&numberposts=1'); 

foreach($posts as $post) { 
    the_title();

    //get next 3 chronological posts and loop
} 

I guess I need to use something like the ‘offset’ parameter, but with a post id instead of a position?

2 Answers
2

For a random offset we might try:

$ppp    = 4;  
$total  = wp_count_posts()->publish;    

$offset = $total < $ppp ? 0 : rand( 0, $total - $ppp );

$posts = get_posts( [
    'posts_per_page' => $ppp,
    'offset'         => $offset
] );

Example:

Let’s take $ppp as 4 and assume $total is 6.

Then are three possibilities for the $offset, namely 0, 1 and 2:

Nr  Offset Selections
1   0      x
2   1      x x
3   2      x x x
4   3      x x x
5   4        x x
6   5          x

so

$offset = $total < $ppp ? 0 : rand( 0, $total - $ppp );

would give:

$offset = rand( 0, 6 - 4 );

or just

$offset = rand( 0, 2 );

Leave a Reply

Your email address will not be published. Required fields are marked *