Skip to content
Advertisement

Count of posts within WP Loop not counting posts to use for div class

I’ve successfully been able to count the number of posts within a loop before, but for some reason this time it won’t work.

<?php $count = 0; if (have_posts () ) { while (have_posts()) { the_post(); $count++; ?>
<div class="post-<?php echo $count; ?>"></div>
<?php } } ?>

Anything Im missing?

Advertisement

Answer

UPDATE After talking to @FlashThunder about this problem. it seems that putting the beginning of the loop in the home.php template and using get_template_part() for the posts that are to be counted won’t work unless they are in the same template, otherwise we would need to use global $count. After putting all of the php in the same template, the posts counted and applied the numeric class to the div’s like I wanted.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement