Placing Ads Between Posts On WordPress

by trigatch4 on May 29th, 2010

Most of my banner advertising has been set it and forget it, only changing what actual ads appear on my site and not where they appear. But recently I had an advertiser request placement on my homepage BETWEEN two posts. I was able to find a simple solution in wordpress to accomplish just this and I thought I’d share for those attempting something similar.

Step 1:
Find “The Loop” in wordpress in the index.php file. It should look something like:

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

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

It may not look EXACTLY like that but it should be something very similar.

Step 2:
Just before that first line of “The Loop” paste the following code:

<?php $postnum = 1; $showads = 1; ?>

Step 3:
Within the “$showads=1″ replace the number 1 with the post number after which you’d like to place an advertisement. If you want an ad between the first and second post, keep it as 1. If you want an ad between the 5th and 6th post, replace the 1 with a 5. So on and so forth.

Step 4:
Find the end of “The Loop” which should look something like:

<?php endforeach; else: ?>

Step 5:
Just before that line which ends the loop, paste the following code:

<?php if ($postnum == $showads) { ?> <<ADD ADVERTISING HERE>> <?php } $postnum++; ?>

Of course you’ll want to replace the “ADD ADVERTISING HERE” bit with actual advertising code. But once you do… you’re all good! At first I would leave that sample text in place and load your site to make sure it is actually working.

Hope this helps!

[Via Tomhanna @ WordPress Codex]

1 Comment

  1. 1. enco wrote on July 26, 2011

    I just found the solution, thank you anyway:

    tamba2.org.uk/wordpress/adsense/

    Enco

Sorry, the comment form is closed at this time.