I'm very new to word press having only installed it on the weekend, I'm fine with HTML & CSS but PHP & Wordpress is alien to me.

I'm trying to display a post from a specific category that changes every day, i've searched everywhere and found the below code whihc works to a point.

I just cant seem to get it to choose from a category number?

Any help or explanation would be much appreciated.

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); ?>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php the_content(); ?>
<?php endforeach; ?>

EDIT Thanks for the suggestions but nothing seems to be working with my existing code, it still continues to pick a completey random post from all categories.


You can change your get_posts $args


$args = array(
    'orderby' => 'rand',
    'category_name' => 'your_category',
    'showposts' => 1
| improve this answer | |
  • thanks for the reply giolliano sulit but still not working, would the first line be overiding the categorty selection? if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) { – BuzzinBilly Aug 1 '17 at 18:29
  • Well you can try to run just the query in the else{ and see if that works. – giolliano sulit Aug 1 '17 at 23:02

Just use WP_Query() to generate your custom query, category parameters.

$category_query_args = array(
    'orderby' => 'rand',
    'category_name' => 'your_category'

$category_query = new WP_Query( $category_query_args );

Note: you could also pass the category slug to the query, via category_name, instead of cat.

And just forward your loop.

if ( $category_query->have_posts() ) : while $category_query->have_posts() : $category_query->the_post();
// Loop output goes here
endwhile; endif;

Hope This will help you.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.