Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
"I see a repetition of 'INSERT ADSENSE CODE HERE' twice" - possibly because of the OR in the conditional statement if ($post_counter == 2 || $post_counter == 3) ? or do you mean somthing else? –  Michael Aug 7 '12 at 18:37

1 Answer 1

up vote 4 down vote accepted

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 } ?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.