How to show AdSense units between posts in WordPress?The most commonly used style for the main index page of a WordPress blog is showing up a list of the posts-excerpts or headlines. Most of the bloggers like to use a paged-navigation under it to scroll through the older posts index (thanks to WP Page Navi). We can not call such layouts the magazine-style layouts completely.

On such a layout of a WordPress blog, one of the best idea to merge ads without losing the effect is showing the ads in the post-index i.e. between the posts-excerpts in the index. As the bloggers around the globe use Google AdSense in plenty, I’m going to explain this with the AdSense units, but you can use ad-units of other advertising programs also. Lets see, how to bring it on without using a plugin.

The file responsible to handle this index page in the background in WordPress theme directory is index.php. All we need to do is to modify the index.php file of our theme.

Note: Before proceeding, make it sure to backup your full WordPress theme.

  1. Edit the index.php file of your theme by going to WordPress Dashboard » Appearance » Editor » Main Index Template
  2. The WordPress index.php file displays the post-index by running a loop function, which looks like the below code:
    <?php while(have_posts()) : the_post(); ?>

    Locate the end of this loop i.e. <?php endwhile; ?> (it completely depends on how your theme is coded, so try to locate the perfect loop enclosure while doing the changes).

    Tip: If you are not able to find that php code, try searching for the keyword “while” in the index.php. You’ll definitely encounter the required code.

  3. Paste the below given code just before <?php endwhile; ?>:
    <?php if (++$PostCount == X) {?>
      <div style="margin: 10px 0;">YOUR_AD_UNIT_CODE</div>
      <?php } ?>
    <?php $postcount++; ?>

    Replace X in the above code with the number of posts after which you want to display the ad unit. Replace YOUR_AD_UNIT_CODE with the code of your AdSense or the other advertising program’s ad unit code.

Similarly, you can display ad units of different kind and dimensions by using the code like this:

  if (++$postcount == 2){ ?>
    <div style="margin: 10px 0;">AD_UNIT_CODE_1</div>
  <?php } elseif (++$postcount == 4){ ?>
    <div style="margin: 10px 0;">AD_UNIT_CODE_2</div>
  <?php }; $postcount++; ?>

Code updated on August 16, 2011

Replace AD_UNIT_CODE_1 and AD_UNIT_CODE_2 with your ad units code and modify the $postcount value according to your need.