How to Implement Adsense Auto Ads on Jekyll Posts

2 minute read

Published:

I’ve made a commitment to reboot my blog, but needed some additional motivation to actually start writing. Money tends to be a good motivator. I figured I’d give Google Adsense a chance. I don’t expect to make much, if anything, in the beginning, but over time I’m hopeful that this could begin to generate some passive income.

Like many people, I’m guilty of using ad blockers myself, so mileage may vary, but as a user, I get why they do this - too many advertisements. With this in mind I didn’t want to pollute my entire site with ads but instead only include them on my posts themselves. This way, I’m only monetizing my actual content, which, I think is a fair use case and might encourage a percentage of users to not block my ads as my site grows.

For the actual implementation I chose to go with the newer Auto ads feature. Traditionally you would be required to choose the type of advertisement and placement on your site, but it’s 2019. We have machines for that. Auto ads now can make all the choices for you thanks to machine learning. You can still opt out of different types of ads if you wish, but in theory, the best ad type and placement will be automatically chosen for each page.

When I rebooted the blog I went with Jekyll, so this approach applies specifically to that platform, but should be very similar for others as well.

The steps to implement Auto ads only on posts in Jekyll is as follows:

  1. Update the _config.yml file to include a new variable autoads that is true by default only for post pages. NOTE: depending on your theme, this section may not already exist.

    defaults:
     # _posts
         - scope:
             path: ""
             type: posts
         values:
             layout: single
             author_profile: true
             read_time: true
             comments: true
             share: true
             related: true
             autoads: true # like this
    
  2. Update the _includes/head.html file to include the standard snippet from Adsense but also wrap the block with an if statement using the Liquid syntax.

    {% if page.autoads %}
     <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
     <script>
         (adsbygoogle = window.adsbygoogle || []).push({
             google_ad_client: "ca-pub-################",
             enable_page_level_ads: true
         });
     </script>
    {% endif %}
    

That’s it. If instead you wanted ads on all pages, there’s no need for the if condition or step one. If you want ads on multiple page types, just default the autoads variable to true for those pages as well. If you have a similar script you want to use only on certain pages, the same steps hold true for that as well. The sky is the limit.

As an Amazon Associate I earn from qualifying purchases.