Title: Counting Loops
Last modified: August 18, 2016

---

# Counting Loops

 *  [jbbrwcky](https://wordpress.org/support/users/jbbrwcky/)
 * (@jbbrwcky)
 * [21 years, 1 month ago](https://wordpress.org/support/topic/counting-loops/)
 * Hello,
 * I searched using ‘counting loops’ but didn’t come across anything pertinent. 
   I am trying to construct my page so that every 3 or 4 posts, I can insert a Google
   Adsense section, how do I achieve this?
 * Thank you,
    Richard

Viewing 4 replies - 1 through 4 (of 4 total)

 *  [Kafkaesqui](https://wordpress.org/support/users/kafkaesqui/)
 * (@kafkaesqui)
 * [21 years, 1 month ago](https://wordpress.org/support/topic/counting-loops/#post-201537)
 * Just stick a variable (let’s say $post_count) with the increment operator into
   The Loop, and check on the value of that. So locate:
 * `<?php if (have_posts()) : while (have_posts()) : the_post(); ?>`
 * in your template, and add $post_count++ to it, like so:
 * `<?php if (have_posts()) : while (have_posts()) : the_post(); $post_count++; ?
   >`
 * Then in The Loop where the ad is to display:
 * `<?php if(4 == $post_count) : ?>`
 * `~ Your adsense code goes here ~`
 * `<?php endif; $post_count = 0; ?>`
 *  Thread Starter [jbbrwcky](https://wordpress.org/support/users/jbbrwcky/)
 * (@jbbrwcky)
 * [21 years, 1 month ago](https://wordpress.org/support/topic/counting-loops/#post-201545)
 * Ahhh! thank you 🙂
 *  Thread Starter [jbbrwcky](https://wordpress.org/support/users/jbbrwcky/)
 * (@jbbrwcky)
 * [21 years, 1 month ago](https://wordpress.org/support/topic/counting-loops/#post-201559)
 * I found a bug with that, the `$post_count = 0;` needs to be before the `endif;`
 * Thanks, it worked perfectly!
 *  [Kafkaesqui](https://wordpress.org/support/users/kafkaesqui/)
 * (@kafkaesqui)
 * [21 years, 1 month ago](https://wordpress.org/support/topic/counting-loops/#post-201569)
 * Hmm, yeah. Guess I was distracted by an upgrade or something…

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Counting Loops’ is closed to new replies.

## Tags

 * [loop](https://wordpress.org/support/topic-tag/loop/)
 * [php](https://wordpress.org/support/topic-tag/php/)

 * 4 replies
 * 2 participants
 * Last reply from: [Kafkaesqui](https://wordpress.org/support/users/kafkaesqui/)
 * Last activity: [21 years, 1 month ago](https://wordpress.org/support/topic/counting-loops/#post-201569)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
