How to add an incrementing number counter inside the WordPress “while” loop

This morning I spent some time figuring out how to add an incrementing number counter inside a WordPress “while” loop and here is how I finally accomplished it:

I defined the first number (in this case, the variable $postnum) before the “while” loop started, like so:

<?php $the_query = new WP_Query( $query_string.'showposts=4' ); ?>
<?php $postnum = 0; ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

Then I added my div with the incrementing number class within the “while” loop, like so:

 
<?php $postnum++;
	echo "<div class='homepagepost-";
	echo $postnum;
	echo "'></div>";
?>

Now my output for each post includes my custom-numbered div:

<div class="homepagepost-1"></div>
<div class="homepagepost-2"></div>
<div class="homepagepost-3"></div>

Meet the author

Libby Fisher is an experienced freelance web developer, recently relocated from Seattle to Boston, and passionate about developing websites that are both aesthetically appealing and intuitively usable - or as she prefers: "beautifully effective."