Friday, December 23, 2011

WordPress - How to Display AdSense only once (only on first post)

I've been looking for many solutions to prevent AdWords ad units part of the post loop to display more than once

Indeed, as the post loop loads before the sidebar, ad units contained within the loop display twice or three times, which prevents ad units in sidebar to show up, because of AdSense three ad units per page limitation

This is a simple trick that works with any WordPress theme


Open the index.php file of your theme in your favorite text editor

Before the loop (starting either with foreach or while) add

<?php
$adsense = 'Put_your_AdSense_code_here';
?>

Now, where you want your ad unit to show up, place

<?php
echo $adsense;
$adsense = '';
?>

From now on, your ad unit should show up only on the most recent post and your other ads, that come later in the code, should show up too

Pretty neat, huh?