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?

2 Answers
2

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

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *