How to: Insert Adsense after the first post

Many bloggers likes to add an Adsense advertisment on their homepage, after the first post. Here’s a very easy way to do it by using a simple php variable as a counter.

This seems to be a common WordPress question, but implementing it on your theme isn't hard at all. The only thing we need is a simple php variable (here named $count) which will count how many posts are listed. If we just listed the first post, we'll display the Adsense code.

Here's the code. Paste it on your index.php file, instead of your current WP loop.

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

25 Responses

Oct 20 2008 08:05

Cool WP adsense trick,

Will try out on my site soon…

Oct 21 2008 08:13

If someone needs a german howto to get this running, see my article on http://www.feldstudie.net/2008/05/13/tutorial-adsense-block-nach-erstem-beitrag-im-loop-indexphp/
Thank you for that nice tutorials… :)

Oct 21 2008 08:21

Thanks for the link Torsten, I’m sure it will help German people :)

Oct 21 2008 08:39

I have written further tutorials. If you’re interested, you may translate and use them. Would just be nice, if you could put a link and a backtrack back to my articles. If you need help with translation, feel free to contact me. :)

Nov 01 2008 17:06

….i am chinese…i want to translate too..hehe

Nov 05 2008 14:56

This is the ‘Recupe’ I was looking for! :)

Thnaks,
Ivan

Nov 07 2008 12:08

Can the same be doen with the Tags pages?

Nov 07 2008 12:49

@SEO Consultant: Sure, you can reuse this code in tag pages :)

Nov 07 2008 14:36

I tried, and made a mess… :)

Perhaps a sample of a full PHP code of he whole archive.php would help us the WP novices? :)

Thanks!!!

Nov 07 2008 17:02

in your archive.php file, find this line:
while (have_posts()) : the_post();

Just before, initialize the $count variable:
&lt?php $count = 0; ?>

After the line paste this code:
<?php $count++;
if ($count < 3) : ?>
//Paste your Adsense code here
<?php the_excerpt(); ?>
<?php else : ?>
<?php the_excerpt(); ?>
<?php endif; ?>
<?php endwhile; ?>

Hope this will help!

Jun 07 2009 20:58

Very Useful. Thanks.

Dec 05 2009 18:05

Thanks for the code… i ll add the code and remove the plugins

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required