Wordpress - 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.

First sort your posts randomly. Then, in outer query, sort the posts from subquery by date.

I would do it with the help of filters posts_request and posts_orderby. The query will be modified only after setting the 'ord_rand_then_date' => true parameter.

add_filter('posts_request', 'se354396_request', 50, 2);
add_filter('posts_orderby', 'se354396_orderby', 50, 2);

function se354396_request( $sql_request, $wp_query )
{
    if ( ! $wp_query->get('ord_rand_then_date', false) )
        return $sql_request;

    $sql_request = 'SELECT sub.* FROM (' . $sql_request . ') sub ORDER BY post_date DESC';
    return $sql_request;
}
function se354396_orderby( $orderby, $wp_query ) 
{ 
    $custom_order = $wp_query->get('ord_rand_then_date', false);
    if ( $custom_order !== true && $custom_order != '1' )
        return $orderby;

    return 'RAND()'; 
}

Example:

$my_posts = get_posts( [
    'ord_rand_then_date' => true,
    'suppress_filters'   => false,
    // other parameters
] );

Tags:

Wp Query