WordPress.org

Support

Support » How-To and Troubleshooting » Random post that will last for a day – daily post

Random post that will last for a day – daily post

  • How do I create a random post that will last for a day, then go to another post. The post should come from a specific category, not just any one.

    Below is what I have tried and it rotates for that daily period, though it takes the post from any category, not from a specific category.

    ‘<?php
    $args = array(‘numberposts’ => 1, ‘category’ => 3,’orderby’ => ‘rand’);

    $lastposts = get_posts( $args );

    if ( false === ( $totd_trans_post_id = get_transient( ‘totd_trans_post_id’ ) ) ) {

    $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));
    $lastposts = get_posts($args);
    }

    foreach( $lastposts as $post ) : setup_postdata($post); ?>
    <div>
    <?php the_content(); ?>
    </div>
    <?php endforeach;
    wp_reset_postdata(); ?>

    Any help would be appreciated.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Evan Herman
    Participant

    @eherman24

    Please format your code better. It’s a little difficult to read through as it sits.

    the correct parameter to query a category ID is cat=3

    so

    $args = array('numberposts' => 1, 'cat' => 3,'orderby' => 'rand');

    codex reference

    Better?


    <?php
    $args = array('numberposts' => 1, 'category' => 3,'orderby' => 'rand');
    $lastposts = get_posts( $args );

    if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) {

    $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));
    $lastposts = get_posts($args);
    }

    foreach( $lastposts as $post ) : setup_postdata($post); ?>

    <div>
    <?php the_content(); ?>
    </div>
    <?php endforeach;
    wp_reset_postdata(); ?>

    I tried changing the category to cat and it did not make a difference.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Random post that will last for a day – daily post’ is closed to new replies.