WordPress.org

Forums

Random post that will last for a day - daily post (4 posts)

  1. cr12-14
    Member
    Posted 1 year ago #

    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.

  2. Evan Herman
    Member
    Posted 1 year ago #

    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

  3. cr12-14
    Member
    Posted 1 year ago #

    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(); ?>

  4. cr12-14
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic