Add Adsense Ads to Your Posts

This post sets out how you can add your Google Adsense code to your blog posts. As this is MakeWithHugo, we’ll be adding them to our Hugo site.

You’ll need a few things before starting, an Adsense account, the snippet of code from Adsense and knowing where you want to put them (or auto ads for the easy option).

There’s a few different ways to achieve this, based on where you want them. We’ll walk through them below.

Option 1: In Your Theme

We can add our code to our theme so it shows on any and every page we want it to.

  1. Create a new file in your layouts directory called adsense.html

  2. Paste in your Adsense Code, like so: (but use your code, not the below, as it will be different)

    1
    2
    3
    4
    5
    6
    7
    8
    
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXX" crossorigin="anonymous"></script>
    <ins class="adsbygoogle"
         style="display:inline-block;width:200px;height:800px"
         data-ad-client="ca-pub-XXXX"
         data-ad-slot="XXXX"></ins>
    <script>
         (adsbygoogle = window.adsbygoogle || []).push({});
    </script>
    
  3. Include the code as a partial in your theme. We’ll pick layouts\_default\baseof.html as our file and insert:

    1
    
    {{ partial "adsense.html" . }}
    

 

Option 2: Let Me Pick

Alternatively, we can add it into our posts. Which is great because we get to pick where exactly. But it does have the downside of we will have to choose every time we write a new post.

  1. Do points 1 and 2 from above.

  2. Find in your theme where we call this:

    1
    
    {{ .Content }}
    
  3. Replace it with:

    1
    
    {{ replace .Content "<!--advert-->" (partial "adsense.html" .) | safeHTML }}
    

    This allows us to simply add <!--advert--> into our posts where ever we want to show our ads.