Support » Fixing WordPress » Query Posts every X amount of hours

  • If this has already been answered, I apologize … I wasn’t able to find it on my own.

    I’m not very good with PHP so I’m completely stuck and looking for help.

    I have a query call for custom post types that pull in both the custom fields, and custom post information. There’s 4 posts (out of 14) that are being called at random. I was able to get this functioning exactly as I wanted it to. The issue I’m having now is I need to alter the query so that it only changes the display every 24 hours instead of everytime the page loads.

    So basically… if Sunday – display 4 posts…. if 24 hours later display another 4 posts.

    These posts need to be completely randomized… my code is below.

    How do I add the ‘change every 24 hour’ factor to it?

    						<?php query_posts("post_type=chapter&orderby=rand&posts_per_page=4");?>
                            <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
                                	<div class="authors">
                                    	<a href="<?php the_permalink();?>"><img src="<?php
    									$post_object = get_field('article_author');
    								if( $post_object ):
    								// override $post
    								$post = $post_object;
    								setup_postdata( $post );
                                		<div class="author-name-home"><?php the_title();?></div>
                                        <div class="author-title-home"><?php echo $first;?> <?php echo $last;?></div>
    						<?php endwhile; endif; wp_reset_query(); ?>

    Thank you in advance

Viewing 1 replies (of 1 total)
  • Moderator keesiemeijer


    Try it with this in your theme functions.php file:

    function day_random_posts_orderby( $orderby ) {
        $seed = floor( time() / DAY_IN_SECONDS );
        $orderby = str_replace( 'RAND()', "RAND({$seed})", $orderby );
        return $orderby;

    Now query for random posts like this:

    $args = array(
    	'posts_per_page' => 4,
    	'orderby'        => 'rand',
    	'post_type'      => 'chapter'
    add_filter( 'posts_orderby', 'day_random_posts_orderby' );
    query_posts( $args );
    remove_filter( 'posts_orderby', 'day_random_posts_orderby' );

    A better way to query would be with new WP_Query:

    consider creating a child theme instead of editing your theme directly – if you upgrade the theme all your modifications will be lost.

Viewing 1 replies (of 1 total)
  • The topic ‘Query Posts every X amount of hours’ is closed to new replies.