How to Show Ads (Google AdSense) in WordPress Sidebar

By Akbar
Google AdSense

I have been using the Google AdSense on my blog for few days now. There are multiple options for showing the Ads in the WordPress. The simplest of them is through WordPress plug-ins. There are many free plug-ins available for WordPress, and some of them are quite powerful and easy to use. But I decided to not use any plug-in for showing Ads, and in this process learned something which might be useful to others as well.

Thought for the Blog list page (the main blog page), I was able to quickly display the Ads in between the posts by simply modifying the “index.php” file and adding the PHP code snippet to show the Ads after every first and seventh post. The following tutorial have step by step instructions on how to do something similar:

The only changed I done was to check for the 1st and 7th post (I show ten posts per page) to display the Ads. The code for this is like:

<?php if ($postCounter == 1 || $postCounter == 7) : ?>
<!-- Google AdSense Code goes here -->
<?php endif; ?>

However, for the left bar, I was having some problem adding the Ads at the correct position. By modifying the “sidebar.php” file in the theme folder, I was able to show the Ads at top or bottom of the Sidebar. However, if I insert the code in between side bar widgets e.g. after Archives but before Tags cloud, it was not appearing in run-time. Debugging the issue, I found that it was because WordPress was generating this section dynamically due to my Widgets settings.

There was however a simple workaround for this, and that’s I went to Appearance -> Widgets settings, and then dragged the “Text” type widget in the left hand side bar on desired location, and in that Text Widget body area, I added the Google AdSense code. The magic happend, and Google Ads started appearing in in the sidebar at my desired location.

The best thing about this technique is that this way I can manage it from the WordPress admin area too, so no need to copy/paste the updated theme files if I plan to change the Ad type or its position.

Tags: , ,