How to get random posts and order them by date

Unfortunately, that will never work. ‘rand’ is a random order, so you always end up with a randomized order, no matter what you put for the date.

In order to do something like what you’re describing, you have to use 'orderby'=>'rand'. Then you can sort the result by date.

$query = new WP_Query(
    [
        'post__in' => $post_id_array,
        'posts_per_page' => $number,
        'orderby' => 'rand'
    ]
);

// Sort the resulting posts array by date
usort( $query->posts, function( $a, $b ) {
    $t1 = strtotime( $a->post_date );
    $t2 = strtotime( $b->post_date );
    return $t1 - $t2;
});

// $query->posts is now sorted and in order by date.

Leave a Comment