Banners in some posts on the index page

You want to put an advert (or anything else) after some posts on the front page, but not others.

There are some fancy programming ways of doing this involving template tags, but this way will do just fine and couldn’t be simpler.

First, find the Loop in your index.php

<?php if (have_posts()) : ?>

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

… the post …

<?php endwhile; ?>

Before the Loop begins, we can initialize a variable to keep count of the posts as they go. Best to put it between the the if and the while statements, like so:

<?php if (have_posts()) :

$count = 1;

while (have_posts()) : the_post(); ?>

And to increase the counter, we can add the command $count++ which we will put just before the endwhile of the loop.
($var++ is a standard shorthand in PHP for $var = $var + 1)

<?php $count++;

endwhile; ?>

Now we can print any html we like, wherever in the post we like, eg. after the post but before the comments (if present) or after the whole lot.

This will print only in the third post of the page…

if ($count == 3) print “An advert or something”;

So to have ads after the 3rd and 7th posts, use the OR operator

if ($count == 3 || $count == 7) {
print “An advert or something”;
}

And take it from there, even numbered posts, only in posts divisible by 3 etc…

Bookmark:
These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Google
  • Facebook
  • Furl
  • NewsVine
  • Reddit
  • StumbleUpon
  • Sphinn
  • Technorati

No Comments

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment