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.
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) : ?>
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; ?>
精彩评论