21

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

<?php while (have_posts()) : the_post(); ?>

这个循环列出了帖子。我需要根据它们的总数将某些类添加到前 3 个。

4

4 回答 4

40

您可以使用 的post_count属性$WP_Query如下所示:

$wp_query->post_count

请注意与 的区别found_posts,它计算尽管与查询匹配但未显示的帖子(例如用于分页)。根据您的具体情况,您可能希望使用其中一种。

于 2013-10-10T18:42:23.333 回答
19

这是一种解决方法:

<?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;
 ?>
于 2013-10-10T18:42:53.187 回答
2

我用这个在我的

<?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; ?>
于 2019-02-21T02:36:05.287 回答
0

最简单的是wc_get_loop_prop( 'total' )

如果您想在模板中获取它并且您无权访问循环变量,就像在您的示例中一样。

于 2022-02-09T22:37:34.810 回答