【发布时间】:2011-03-19 11:59:38
【问题描述】:
在循环中,我想检索当前的帖子数。
例如,在每 3 个帖子之后,我想插入一个广告。
那么,如何获取循环计数的值?
【问题讨论】:
在循环中,我想检索当前的帖子数。
例如,在每 3 个帖子之后,我想插入一个广告。
那么,如何获取循环计数的值?
【问题讨论】:
您可以使用WP_Query对象实例的current_post成员来获取当前的后迭代;
while ( have_posts() ) : the_post();
// your normal post code
if ( ( $wp_query->current_post + 1 ) % 3 === 0 ) {
// your ad code here
}
endwhile;
注意,如果您在函数中使用它,则需要将 $wp_query 全球化。
【讨论】:
true,因为 0 模数任何实数始终为 0。广告代码在您的第一个之前被错误地插入发布、第四篇、第七篇等。更新后的代码应为:($wp_query->current_post + 1) % 3。
为什么不增加一个变量然后在需要时显示您的广告?
while(LOOP)
echo $i%3==0 ? $ad : '';
$i++
【讨论】:
不知道为什么,但是建议的方法对我不起作用,我不得不求助于以下方法
$loop_counter = 1;
while( $query->have_posts() )
{
//Do your thing $query->the_post(); etc
$loop_counter++;
}
如果你问我,比玩全局变量更安全。
【讨论】: