Insert image or ad script after 3 posts using the loop

The question:

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,

<?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?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 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 } ?>

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment