Select random post every day

I am looking for a script to select 1 random post per day in WordPress.
I found the code below, but this keeps gathering a new post every time I refresh the page:

 <?php
function force_random_day_seed($orderby) {
    $seed = floor( time() / DAY_IN_SECONDS );
    $orderby=str_replace('RAND()', "RAND({$seed})", $orderby);
    return $orderby;
}
        add_filter('posts_orderby', 'force_random_day_seed');
$args = array('numberposts' => 1, 'orderby' => 'rand', 'post_type' => 'listing');
$totd = get_posts($args);
remove_filter('posts_orderby', 'force_random_day_seed');
foreach( $totd as $post ) : ?> 
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; ?>

Any ideas?

2 Answers
2

Note that the posts_orderby filter is not available for get_posts() where suppress_filters is true by default.

You can use WP_Query instead:

$args = [ 
    'posts_per_page'      => 1, 
    'orderby'             => 'rand', 
    'post_type'           => 'listing', 
    'ignore_sticky_posts' => true,
];

add_filter( 'posts_orderby', 'force_random_day_seed' );
$q = new WP_Query( $args );
remove_filter( 'posts_orderby', 'force_random_day_seed' );

if( $q->have_posts() )
{
    while( $q->have_posts() )
    {
        $q->the_post();
        the_title();
    }
    wp_reset_postdata();
}
else
{
    _e( 'Sorry no posts found!' );
}

It’s also possible to skip your posts_orderby filter callback and just use transients to store the results for 24 hours.

Leave a Comment