Wordpress loop - how to count items

2019-04-19 04:20发布

Is there a way to get a number of items within Wordpress loop code:

<?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条回答
淡お忘
2楼-- · 2019-04-19 05:00

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; ?>
查看更多
疯言疯语
3楼-- · 2019-04-19 05:02

You can use the post_count property of $WP_Query, like so:

$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.

查看更多
乱世女痞
4楼-- · 2019-04-19 05:11

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;
 ?>
查看更多
登录 后发表回答