WordPress and Google Ads
WordPress developers are offering a lot of plugin for users to install. Most of the admins don’t know that plugins are adding extra code to the core, making WP sites slower.
Today I’m gonna talk about how to insert google ads in home page posts. Google doesn’t allow more than 3 ads per page and with WP displaying all posts in a loop you have two options:
- use a plugin to manage ads code and how to display them on site
- learn how to edit wp theme and do the modifications by yourself (the code is very simple)
1. Go in theme editor (theme-editor.php) and open index.php file (main index template).
2. Find the line
1 | <?php if (have_posts()) : ?> |
Replace it with
1 2 | <?php if (have_posts()) : ?> <?php $post_count_g = 0; ?> |
$post_count_g counts number of posts in the loop
We know we have 10 or 20 posts per page and only 3 ads to display but we don’t know when to stop displaying the ads.
3. Find the line:
1 | <p class="postmetadata"> |
Replace it with:
1 2 3 4 5 6 7 8 9 10 | <?php if ($post_count_g < 3) { ?> GOOGLE ADS CODE HERE <?php } $post_count_g++; ?> <p class="postmetadata"> |
On each iteration of while (have_posts()) we check if post_count_g is below 3, when it reaches 3 ads are no longer displayed.
Depends on your ad type you can change the 3 value ($post_count_g < 3) to whatever ads number are you allowed to display in your page.
Enjoy blogging
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.
