Adding Ad Every nth Post on Loop with Customizations

I am working on a site where I would like to add some ad code every 3rd or 4th post. It is a Masonry style blog with multiple post types. I know how to do the custimazation to make the ad fit in with the masonry; however, I don’t know where to insert the counter/ad code via this customized loop:

<?php $options = get_option('salient');
			
			$blog_type = $options['blog_type'];
			if($blog_type == null) $blog_type = 'std-blog-sidebar';
			
			$masonry_class = null;
			
			//enqueue masonry script if selected
			if($blog_type == 'masonry-blog-sidebar' || $blog_type == 'masonry-blog-fullwidth' || $blog_type == 'masonry-blog-full-screen-width') {
				$masonry_class = 'masonry';
			}
			
			if($blog_type == 'masonry-blog-full-screen-width') {
				$masonry_class = 'masonry full-width-content';
			}
			
			if($blog_type == 'std-blog-sidebar' || $blog_type == 'masonry-blog-sidebar'){
				echo '<div id="post-area" class="col span_9 '.$masonry_class.'">';
			} else {
				echo '<div id="post-area" class="col span_12 col_last '.$masonry_class.'">';
			}
	
				if(have_posts()) : while(have_posts()) : the_post(); ?>

Any help would be appreciated.

Well there are many tutorials with regards this issue. Basically, what you need to do is that every time the post reaches say 3 or 4 (as per your requirement) you insert the ad code and then reset the counter. For example if you want to insert code on every 3rd place then if the counter is 2 you will need to add because after second position, you want the code. Similarly you can do it at 3rd if you want it on 4th position.
You have a counter say $postcounter = 0; then in the loop add $postcounter++ so when the $postcounter == say 2 (or 3) begin the advertise insert loop.

Easier to create a new widget which outputs before or after every 3rd or 4th post on your home page and/or any archive pages.

The code will depend on which theme you’re using as some include hooks and some don’t.


if(have_posts()) : while(have_posts()) : the_post();

This is where your loop starts, so you would initialize your counter before this line. After that its just a matter of incrementing once in the loop and checking which post you are on before you render an ad and when you render the ad you can reset the counter back.