In this guide you’ll learn how to display Adsense on just your first post within the Loop. Sure, there may be plugins that will do this for you. This guide, however, will use code examples to accomplish the same thing by editing your WordPress theme.

The first step is to open up your index.php file in your theme editor. Find the following line:

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

Just above that, insert the following like this:

<?php $i = 1; ?>
<?php if(have_posts()) : ?>

Now, scroll down a bit until you find this line:

<?php endwhile; ?>

Insert the following above it, like so:

<?php $i++; ?>
<?php endwhile; ?>

The final step is to insert your AdSense code. Locate where exactly you’d like it within the Loop, and place it between a conditional tag like this:

<?php if ($i == 1) { ?> [YOUR ADSENSE CODE HERE] <?php } ?>

And that’s all you have to do. You can be creative with this code as well. You could add a certain css style class to the top post in your Loop. It doesn’t even have to be the first either, as you can just change the number in $i == 1 to whatever you want. This same method can be used in other archive templates such as archive.php.

Kyle Eslick is WordPress enthusiast who took his passion for WordPress to the next level in 2007 by launching as a place to share hacks, tutorials, etc. Follow Kyle on Twitter @KyleEslick!

  1. Hayes Potter says:

    very nice thanks.

  2. This article saved me :)) Thanks a lot ­čśë

  3. foodie says:

    Your code isn’t working properly. It broke my site. I think there is an unexpected end in it. Anyways, I deleted your code and got my site working again.

  4. I applied the code to my site and it worked perfectly. I was using Adsense Integrater until I found out a couple days ago that they were replacing my Adsense affiliate code with theirs. I have removed the plugin and now have all my ads manually inserted so at least I know no one will be stealing clicks from me.

  5. says:

    i’m just learning to write wp plugin.
    this article do what i want to.
    but i do not want to hack themes.

    could you please make this super simple hack into super simple plugin?


Trackbacks/Pingbacks »

  1. Adsense reklam?n?z? ilk Postun arkas?ndan nas?l g├Âr├╝nt├╝leyeceksiniz? | alialtugkoca says: