Exclude Adsense ads from specific posts on Hugo

How to manually or automatically exclude Google Adsense ads from specific posts or pages on Hugo static site generator.


Some blog posts are exceptionally short where ads would dominate the content of the page resulting in violation of Adsense policies.


I am assuming you have experience with Hugo Templating and already have ads inserted into your template.

Solution - Manual method

Adding custom condition to display into Hugo template

Add a condition statement that needs to be evaluated to true for the ads to be displayed:

{{ if ne .Params.adsenabled false }}
<!--paste your Adsense Javascript code here-->
{{ end }}

Excluding ads from specific post or page

To exclude specific pages, define a custom param called adsenabled for the post/page. This should be placed within the opening and closing front matter.

adsenabled = false

For pages that should have ads displayed, do not add adsenabled param.

More granular control

In the solution above, it is an all or nothing setting whereby if you enable then all ads are displayed; otherwise none.

One way to have more granular control is by defining multiple parameters instead of one. For example:

leaderboardadenabled = false
sidebaradenabled = false
bottomadenabled = false

Then the templates should of course be modified to check against the same param names.

{{ if ne .Params.leaderboardadenabled false }}
<!--paste your Adsense Javascript code here-->
{{ end }}

Solution - Automatic method

Instead of manually needing to set which posts should have ads or not, Hugo has a few Page Variables that can be used to make this decision automatically such as:

  • FuzzyWordCount
  • ReadingTime
  • WordCount

For example:
If ReadingTime is greater than 1 minute, include ads:

{{ if gt .ReadingTime 1 }}
<!--paste your Adsense Javascript code here-->
{{ end }}

I prefer automatic. :)