How to Insert Adsense Code After First, Second or Nth Post in WordPress

How to add AdSense code after first, second or nth post on WordPress homepage, or archive pages? This is one of the most frequently asked question. And its also very easy to implement. You just need to modify the WordPress loop on appropriate template page.

To insert AdSense code after first post on your blog’s homepage, open the index.php, or home.php depending upon your theme. Then find the line,

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

And add the following code just before it,

<?php $adcounter = 0; ?>

Now, again, look for the line,

<?php endwhile; ?>

And add this code, just before it,

<?php $adcounter++; ?>

Now add your AdSense code inside the loop. The code should be put inside an if condition. The condition depends upon where would you like it insert the ad (like after the first post, or second post etc.). The condition will look something like this,

<?php if ($adcounter == 1) : ?>

<!-- Your AdSense Code here -->

<?php endif;?>

For example, to insert the AdSense code just after the first post, you’ll modify the loop like this,

<?php if (have_posts()) : ?>
<?php $adcounter = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php if ($count == 1) : ?>
          //Paste your Adsense code here
          <?php the_excerpt(); ?>
<?php else : ?>
          <?php the_excerpt(); ?>
<?php endif; ?>
<?php $adcounter++; ?>
<?php endwhile; ?>
<?php endif; ?>
share on twitter

Comments

  1. Puma says:

    Thank you! This article helped me place the ad as required.

Leave a Reply