This guest post was written by Leland of Theme Lab, where he has released over 50 WordPress themes. In addition to themes, Theme Lab also provides some WordPress guides. If you have WordPress knowledge and are interested in writing a post for Hack WordPress, please contact us.

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.

You can display ads with WordPress in other ways as well, including plugins such as WhyDoWork Adsense Plugin (formerly Shylock Adsense).

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!
Digg This | Stumble it | Add to Del.icio.us | | Print This

There Are 7 Responses So Far. »

  1. 1 Hayes Potter
    Sunday, May 11th, 2008 at 4:29 am

    very nice thanks.

  2. 2 Pavel Ciorici
    Wednesday, May 21st, 2008 at 4:26 am

    This article saved me :)) Thanks a lot ;)

  3. 3 foodie
    Friday, March 13th, 2009 at 6:55 pm

    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. 4 Signupandmakemoney
    Saturday, May 16th, 2009 at 6:58 pm

    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. 5 dennyhalim.com
    Thursday, May 28th, 2009 at 2:29 am

    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?

    tia



Leave A Comment