Show Ads or Other Content Only in the First Three Posts

Posted on February 5th, 2011

Advertising may require you to limit the number of advertisements on your page to three. For some, this is three too many. For others, it’s far too few. Still others feel that it’s just the right amount.

Regardless of your feelings, here is a trick that will enable you to limit the number of posts that displays some specific content — ads, images, scripts, whatever you want. Check out the three indented lines in the following loop:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php if ($wp_query->current_post < 3) { ?>

<!– any content here will be displayed only in first three posts –>

<?php } ?>

<?php endwhile; else: ?>

<?php endif; ?>

Here we gett a loop.  In this loop, we specify a condition that says, “if this is one of the first three posts, display this content.” And that’s the magic. Of course, you can use whatever content you would like, and there is nothing special about the number “3” either.