Retrieving the first post published after a random date can be achieved with a WordPress date query combined with the wp_rand()
function.
For the wp_rand()
function, you just have to supply it the minimum and maximum number. We can use this function to return a random timestamp between the current time and the timestamp of the first published post. The function time()
will give the current time as a unix timestamp and this could be your maximum number. For the minimum number, the timestamp of the first published post could be used.
This minimum number could be hardcoded, since it's unlikely to change, but if you wanted to run a query to find the timestamp of the first published post, that would look like this:
$first_post_query = new \WP_Query( [
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'ASC',
'ignore_sticky_posts' => true,
'no_found_rows' => true,
] );
$first_post = $first_post_query->posts[0];
$min_time = strtotime( $first_post->post_date_gmt ) + 1;
Now that we have a minimum number, we can calculate a random timestamp and convert it into a date like this:
$random_timestamp = wp_rand( $min_time, time() );
$random_date = date( 'm/d/Y H:i:s', $random_timestamp );
This random date can be used in a WP_Query to retrieve a random post:
$query = new \WP_Query( [
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'date_query' => [
'before' => $random_date,
],
'ignore_sticky_posts' => true,
'no_found_rows' => true,
] );
$random_post = $query->posts[0];
The ignore_sticky_posts
and no_found_rows
parameters are to improve the performance of the query.
I would expect this query to return fairly random posts for a site with regularly spaced out content. For example, if posts were published consistently every day over the time period in question. However, if the publishing cadence was erratic, then this would produce suboptimal results.