我有一个自定义的帖子类型“quotes”,我想每天在主页上显示一个随机条目。
这是我当前必须显示内容的代码:
<?php query_posts( \'post_type=quote&orderby=rand&showposts=1\' ); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php if ( has_post_thumbnail() ) {
the_post_thumbnail( \'thumbnail-quote\' );
} else { ?>
<img src="<?php bloginfo(\'template_directory\'); ?>/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 endwhile; endif; ?>
EDIT: 根据这些有用的建议,我现在有如下内容:
<?php
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.
$seconds_until_next_day = strtotime(\'tomorrow\') - time();
set_transient( \'random_quote\', $quotes, $seconds_until_next_day );
}
foreach ( $quotes as $post ) : setup_postdata( $post );
if ( have_posts()) : while (have_posts()) : the_post();
if ( has_post_thumbnail() ) {
the_post_thumbnail( \'thumbnail-quote\' );
} else { \'<img src="\' . bloginfo(\'template_directory\') .\'/img/thumb1.jpg" alt="University of Lincoln" class="quote_person" />\'
echo \'<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" id="thequote">\' . the_field(\'quote\') . \'</div>
<div class="quote_source white hstack">\' . the_field(\'attribution\') . \'</div>
</div>
\'; }
endforeach;
wp_reset_postdata();
?>
我不太确定foreach的说法是否正确。