Insert image or ad script after 3 posts using the loop

There are many scripts/hacks out there to insert ads into the middle of the post (after ‘x’ number of paragraphs), however I haven’t found a good enough script that can do the above.

This is the script that comes close,

Read More
<?php $post_counter=0; ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php require('post.php'); ?>
<?php
$post_counter++;
if ($post_counter == 2 || $post_counter == 3) { ?>
INSERT ADSENSE CODE HERE
<?php } ?>
<?php endwhile; ?>

Taken from here. But my index.php uses this instead:

<?php
$page_num = $paged;
if ($pagenum='') $pagenum =1;
query_posts('cat=-3&showposts=6&paged='.$page_num); ?>
            <?php if (have_posts()) : ?>
        <?php while (have_posts()) : the_post(); ?>
            <?php get_template_part('includes/index-loop'); ?>
            <?php endwhile; wp_reset_postdata(); wp_reset_query(); ?>
            <div class="clear"></div>

        <?php else : ?>
        <?php endif; ?>

I tried putting in the

<?php
$post_counter++;
if ($post_counter == 2 || $post_counter == 3) { ?>
INSERT ADSENSE CODE HERE
<?php } ?>

before endwhile, but I see a repetition of ‘INSERT ADSENSE CODE HERE’ twice. Any suggestions?

Related posts

Leave a Reply

2 comments

  1. instead of a post counter, you could use the variable $wp_query->current_post – which starts with 0 for the first post in the loop;

    for some output after the third post, use for instance this before the line with endwhile;:

    <?php if( $wp_query->current_post == 2 ) { ?>
    DO SOMETHING
    <?php } ?>
    
  2. <?php $ad_positions = array(2,3,4,5,6); // array of preset possible ad positions 
    $numb = $ad_positions[rand(0, count($ad_positions) - 1)]; 
    
    if( $wp_query->current_post == $numb ) { ?> 
    DO SOMETHING 
    <?php } ?>
    

    If anybody need to show the ad in random positions, above code will help in the wordpress loop. Thank you.