How To Add Ad Codes Between 2 Posts On Home Page/ Front Page

Ever Had an Issue adding advertising codes like Google AdSense ad codes on Front Page?

It is actually best to add the ad codes Through a theme settings or a third party  plugin, but at times it does not help.

Sometimes you might have to add different ad codes after each post so the use of plugin is not possible.

You can use this method to add the codes but If you update the theme the changes have to be made again.

How To Add Ad Codes Between 2 Posts On Home Page Front Page

The steps to insert the ad codes are as follows;

(Before making changes to any of the files take a back up of the files you are going to change)

  1. Login to your WordPress administration panel
  2. Select Appearance -> Editor from the navigation menu
  3. On the Theme Editor page, you will see a list of “theme files” to the right of the page. Select the “Main index template” (index.php).
  4. Find the following line

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

  1. Above it add the following line

<?php $count = 1; ?>

Comments:-$count is the variable and you have to assign a value to that variable. In this case the value is 1.

  1. Find the line <?php endwhile; ?>
  2. Add the following code directly above it (replace AdSense Code with your code)

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

Ad Code 1

<?php elseif ($count == 2) : ?>

Ad Code 2

<?php endif; $count++; ?>

Comment:-We can count how many times the loop has cycled by adding the block of code above. Remember at the start we added <?php $count = 1; ?>, well above we check $count, if count is 1 we place AdSense code 1, if its 2 we place AdSense code 2.NOTE : To change which post your AdSense is placed under, simply change the count number, for example: $count == 2 will place the AdSense under post 2

  1. Find the line <?php endwhile; ?>
  2. Below it add the following code:

<?php if ($count != 2 AND $count != 3 ) : ?>

Ad Code 3

<?php endif; ?>

Comment:-The adsense will be added after the very last post on the home page because it’s been added after <?php endwhile; ?>It also tells us that if the above 2 ads are not the last ads than add Google AdSense Code 3 at the end.

  1. Click Save, then go view your site to confirm that the AdSense has been added to the first post listing on your home page. Note – if you want the same thing to show on the category or archive pages then that’s easy. You just need to copy and paste what you‘ve done to either your archive.php or category.php.

Leave a Reply

Your email address will not be published. Required fields are marked *