I need to get some random posts and order them by date.

To get random posts I used the following:

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

To order by date I tried this:

'orderby' => ['rand' => 'ASC', 'date' => 'DESC']

But it does not work correctly. How can I do this?

2 Answers
2

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.

Tags:

Leave a Reply

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