AgentWP

  • Tutorials
  • Themes
  • Plugins
  • Services
  • Contact

How To Insert Adsense Code After First, Second or Nth Post in WordPress

If you are running a traditional blog style WordPress website that shows a list of posts on home page and its monetized by Google Adsense, you may want to display Adsense ads after first, second or nth post on the home page of your website. It will definitely increase the Adsense revenue of your website.

increase adsense earning

To insert AdSense ad code after first post on your blog’s homepage, open the index.php, home.php or front-page.php file, depending upon your WordPress theme. Then find the line,

<?php while (have_posts()) : the_post(); ?>

And add the following code just before it,

<?php $adcounter = 0; ?>

Now, again, look for the line,

<?php endwhile; ?>

And add this code, just before it,

<?php $adcounter++; ?>

Now we will add the AdSense ad unit code inside the WordPress loop we just edited. The code should be put inside an if condition. The condition depends upon where would you like it insert the ad (like after the first post, or second post etc.). The condition will look something like this,

<?php if ($adcounter == 1) : ?>

<!-- Your AdSense Code here -->

<?php endif;?>

For example, to insert the AdSense code just after the first post, you’ll modify the loop like this,

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

Add multiple if conditions with different Adsense ad unit codes to add them after second, third or nth post as needed. If you see any issues implementing this solution, you can hire me to do it for you.

Get useful WordPress related tricks, tips, tutorials and reviews delivered straight to your inbox.

StudioPress - Premium Wordpress Themes
ElegantThemes - Premium Wordpress Themes

Copyright © 2022 · AGENTWP · All Rights Reserved

Copyright © 2022 · awp on Genesis Framework · WordPress · Log in