tepad.no
tepad.no

Reputation: 333

Wordpress loop - how to count items

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.

Upvotes: 23

Views: 71801

Answers (4)

Martzy
Martzy

Reputation: 85

The easiest would be wc_get_loop_prop( 'total' )

If you want to get it in a template and you don't have access to the loop variable, like in your example.

Upvotes: 0

Cutting Edge Hobbies
Cutting Edge Hobbies

Reputation: 99

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; ?>

Upvotes: 4

Bojana Šekeljić
Bojana Šekeljić

Reputation: 1056

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;
 ?>

Upvotes: 20

Sunyatasattva
Sunyatasattva

Reputation: 5840

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.

Upvotes: 45

Related Questions