Wordpress 循环 - 如何计算项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19303556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wordpress loop - how to count items
提问by tepad.no
Is there a way to get a number of items within Wordpress loop code:
有没有办法在 Wordpress 循环代码中获取多个项目:
<?php while (have_posts()) : the_post(); ?>
This loop lists the posts. I need to add certain classes to first 3 depending on the total number of them.
这个循环列出了帖子。我需要根据它们的总数将某些类添加到前 3 个。
回答by Sunyatasattva
You can use the post_count
propertyof $WP_Query
, like so:
您可以使用post_count
属性的$WP_Query
,就像这样:
$wp_query->post_count
Be aware of the difference with found_posts
, which counts the posts which, though matching the query, are not being displayed (e.g. for pagination). You might want to use one or the other depending on your particular situation.
请注意与 的区别found_posts
,它计算虽然匹配查询但未显示的帖子(例如用于分页)。您可能希望根据您的特定情况使用其中一种。
回答by Bojana ?ekelji?
Here's one way to go about it:
这是一种解决方法:
<?php
$count = 0; //set up counter variable
while (have_posts()) : the_post();
$count++; //increment the variable by 1 each time the loop executes
if ($count<4) {
// here put the special code for first three
}
// here put the code for normal posts
endwhile;
?>
回答by Cutting Edge Hobbies
I used this in mine
我用这个在我的
<?php $count = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post(); $count++;?>
<div class="col-lg-3">
<h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
<p><?php the_excerpt();?></p>
</div>
<?php if ($count==4) { $count = 0;?>
<div class="clearfix"></div>
<?php } ?>
<?php endwhile; endif; ?>