我们能把WordPress循环计算在内吗

时间:2017-09-23 作者:The WP Intermediate

我们可以计算WordPress循环并将其存储在变量中吗?

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php $post_id = get_the_ID(); ?>
    <?php get_template_part(\'content\',\'home\'); ?>
       some code to be executed
<?php endwhile; ?>
<?php endif; ?>
我想要的是,对于每5篇文章,应该执行提取的ceratin代码(示例新闻稿)→ 这意味着在循环中,每隔5h、10th、15th、\\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu无限个帖子(5n,n>=1)应该执行代码。

2 个回复
最合适的回答,由SO网友:Michael 整理而成

$wp_query->current_post 是内置循环计数器,循环中的第一个post从0零开始。

所以这条线some code to be executed 可以转换为:

<?php if( $wp_query->current_post > 0 && $wp_query->current_post % 5 == 0 ) { ?> some code to be executed <?php } ?>

SO网友:Pratik bhatt

请检查此代码段

 <?php  $i=0; 
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    <?php $post_id = get_the_ID(); ?>
    if($i%5 == 0)
    {\\\\code to be executed}
    <?php get_template_part(\'content\',\'home\'); ?>
       some code to be executed
<?php $i++;endwhile;  ?>
<?php endif; ?>

结束