Wordpress循环 - 如何计算项目

tep*_*.no 14 wordpress loops count

有没有办法在Wordpress循环代码中获取许多项目:

<?php while (have_posts()) : the_post(); ?>
Run Code Online (Sandbox Code Playgroud)

此循环列出了帖子.我需要将某些类添加到前3个,具体取决于它们的总数.

Sun*_*tva 24

您可以使用post_count属性$WP_Query,就像这样:

$wp_query->post_count
Run Code Online (Sandbox Code Playgroud)

请注意与之相关的差异found_posts,这些差异虽然与查询匹配,但未显示(例如,用于分页).您可能希望根据您的具体情况使用其中一个.

  • 如果你愿意,你也可以使用 `$items = count($posts)` :) (2认同)

Boj*_*jić 14

这是一种方法:

<?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;
 ?>
Run Code Online (Sandbox Code Playgroud)

  • @Sunyatasattva“我需要将某些类添加到前 3 个”-他需要计算并测试它是否小于 4 以向它们添加特殊类......否决?真的吗? (2认同)
  • 在引用的句子之后*“取决于它们的总数。” *他并不需要将类添加到前三个中,这些类将取决于总数。我拒绝投票,因为这不能回答问题。如果您编辑答案以实际解决OP问题,则总是可以收回该票。 (2认同)
  • @sksallaj我明白什么是循环和什么计数器,我相信你误读了OP问题,并根据你不了解Wordpress的第二个评论.OP将决定谁误解了.在任何情况下:如果你只是想要一个计数器,Wordpress` $ WP_Query`有方便的[`current_post`属性](http://codex.wordpress.org/Class_Reference/WP_Query#Properties),它将为你提供当前的循环索引. (2认同)