WordPress Loop post count

If you want to count posts in the WordPress loop to, for example, add a class to the last post (to style it, for example with a float:right;), do the following:

  1. Start with the normal WordPress loop, and in my example a simple Div.
  2. Create a variable: “post_counter” and set it equal to 0 and place it above the Loop.
  3. Place inside the loop the $post_counter variable and let it count by $post_counter++;. So by each time the loop creates a new post the $post_counter, counts up by 1.
  4. Now make an if statement inside the Div which checks if $post_counter is equal to 2, then echo out: class=”last”.

The code:

<?php $post_counter = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post(); 
$post_counter++; ?>
<div <?php if($post_counter == 2) : echo "class=\"last\""; endif; ?>></div>

<?php endwhile; else: ?>
<?php endif; ?>

Suppose you want to count more times, because you want to float, for example, each time 2 Divs next to each other and always want to give the last of the 2 Divs in a row the class=”last” (to style it, for example with a float:right;) then you should reset the $post_counter after the if statement and let it count again.

This is done as follows (watch the $post_counter reset in red):

<?php $post_counter = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post(); 
$post_counter++; ?>
<div <?php if($post_counter == 2) : echo "class=\"last\""; $post_counter = 0; endif; ?>></div>

<?php endwhile; else: ?>
<?php endif; ?>
Advertisements

2 thoughts on “WordPress Loop post count

  1. Instead of resetting the post_counter you can use the remainder. eg. if($post_counter % 2 == 0)
    This will return true when the post_counter is dividable by 2.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s