tags:

views:

42

answers:

2

I want to put in and ad code after every 6 post on my blog. I cant really figure out how to break out of the foreach and insert the ad code.

+2  A: 

This link will help you. Third title says: Insert Ads After The First Post

Change the code for 6 where it says 2:

<?php if (have_posts()) : ?> // Here we check if there are posts
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?> // While we have posts, add 1 to count
  <?php if ($count == 6) : ?> // If this is post 6
          //Paste your ad code here
          <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> // post title
          <?php the_excerpt(); ?> // You may use the_content too
   <?php else : ?> // If this is not post 6
          <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
          <?php the_excerpt(); ?>
  <?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>

UPDATE: As Gordon noticed, you asked for code every 6 posts (sorry I missed that on my first read). So the code should be:

<?php if ($count % 6 == 0) : ?>
Fernando
The OP would like to do this after every 6th post, not just the 6th post. You'd either have to reset $count after the 6th or use modulo for the condition. Also, if the OP just wants to insert additional code, there is no need to duplicate the posts code. Just check if it's the 6th and add the additional code. Then close the if block and just add the regular posts code.
Gordon
A: 

As what @Gordon commented, here's how I'd re-factor that code;

<?php if (have_posts()) : $count = 1; while (have_posts()): ?>

    <?php if ($count == 6) : ?>

          // Paste your ad code here

    <?php $count = 0; endif; ?>    

    <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
    <?php the_excerpt(); ?>

<?php $count++; endwhile; endif; ?>
TheDeadMedic