首先,你真的不应该使用query_posts()
. Read this excellent explanation why.
那么这是一个完美的用例transients.
您只需获取一次帖子,然后使用Transients API将其缓存24小时。
if ( false === ( $quotes = get_transient( \'random_quote\' ) ) ) {
// It wasn\'t there, so regenerate the data and save the transient
$args = array(
\'post_type\' => \'quote\',
\'orderby\' => \'rand\',
\'posts_per_page\' => \'1\'
);
$quotes = get_posts( $args );
//Now we store the array for one day.
//Just change the last parameter for another timespan in seconds.
set_transient( \'random_quote\', $quotes, DAY_IN_SECONDS );
}
如果您的目标是将其绑定到日历日,而不是最后一个请求后的24小时,请将最后一行替换为以下内容。(
props 到
chaos)
$seconds_until_next_day = strtotime(\'tomorrow\') - time();
set_transient( \'random_quote\', $quotes, $seconds_until_next_day );
获得数据后,您可以按任何方式显示数据:
foreach ( $quotes as $post ) : setup_postdata( $post );
[...]
the_title();
[...]
endforeach;
wp_reset_postdata();
See this link for more examples.
EDIT:
这应该在您的特定情况下起到作用:
foreach ( $quotes as $post ) : setup_postdata( $post );
if ( has_post_thumbnail() ) {
the_post_thumbnail( \'thumbnail-quote\' );
} else { ?>
<img src="<?php echo get_stylesheet_directory_uri (); ?>/img/thumb1.jpg" alt="x" class="quote_person" />
<?php } ?>
<div class="quote_container">
<span class="quote_intro hstack">Quote of the day:</span><a class="quote_tweet hstack" href="#">Tweet this quote <i class="fa fa-twitter"></i></a>
<div class="quote_message white gstack"><?php the_field(\'quote\'); ?></div>
<div class="quote_source white hstack"><?php the_field(\'attribution\'); ?></div>
</div>
<?php endforeach;
wp_reset_postdata();