October 08, 2015
Adding increasing increments to loops can help with styling elements, and revealing additional content. Here are few examples to implement counters with php.
Using the loop:
if (have_posts()) {
while(have_posts()) {
$count = 1;
the_post() {
echo $count;
}
$i++;
}
}
Different version of counting with the_loop:
if (have_posts()) { $count = 0;
while(have_posts()) {
the_post() {
echo ++$count;
}
}
}
Using foreach:
$i = 0;
foreach ($items as $post) {
$i++;
}
Update: March 29, 2016
Count every third iteration in order to add styles, div wrappers, or further customizations to the layout with a pattern counter:
<?php if ($i % 3 == 0) { ?>
<hr/>
<?php } ?>
Altogether:
$i = 0; // change this number to one or it will skip the first item in the loop
foreach ($counter_post as $post) : setup_postdata($post); $i++;
<li>
<h2><?php the_title(); ?></h2>
</li>
<?php if ($i % 3 == 0) { ?>
<hr/>
<?php } ?>
<?php endforeach; wp_reset_postdata(); ?>