How To: Display Adsense On Your First Post Within The Loop
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).
—
Enjoy writing about WordPress? Get yourself more exposure by joining the Hack WordPress writing team!
Digg This Post! | Stumble This Post! | Add this Post to Del.icio.us | Google Bookmark This Post! | Netscape it! | No comment
Hack WordPress © 2008
—
Related Articles at Hack WordPress:
- Ultimate Guide to the WordPress Loop
- How To: Converting Your Category Pages to Display Post Titles
- Insert AdSense Into Posts with Shylock AdSense
- How To: Alternating Your Post Background Colors
- How To: Make your WordPress Search Results Unlimited
- How To: Separate WordPress Comments and Trackbacks