How do I create a random post that will last for a day

How do I create a random post but it shouldnt be change when the page is refreshed

I want a random post that will last for a day and after 24 hours or a day,
it will change randomly the post ,
will be that possible? or are there a plugin that exactly does that ,

actually what Im trying to create is like a “Random Tip For the Day”, you know something like that

I hope someone understand my question

please help,any help will be appreciated.

4 Answers
4

Here is some code doing what you’ve asked and using the ideas others have highlighted:

<?php
if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) {
     $args = array('numberposts' => 1, 'orderby' => 'rand');
     $totd = get_posts($args);
     $midnight = strtotime('midnight +1 day');
     $timenow = time();
     $timetillmidnight = $midnight - $timenow;
     echo $midnight;
     echo ",".$timenow;
     set_transient('totd_trans_post_id', $totd[0]->ID, $timetillmidnight);
} else {
    $args = array('post__in' => array($totd_trans_post_id));
    $totd = get_posts($args);
}

foreach( $totd as $post ) : setup_postdata($post); ?>
    <div>
        <a href="https://wordpress.stackexchange.com/questions/17056/<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php the_content(); ?>
    </div>
<?php endforeach; ?>

get_posts() help Plus the way I have coded it should make the Tip of the Day post change at midnight every day.

This can be improved upon because we are showing random there is nothing stopping the same post showing twice in a row…

Leave a Comment