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.
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 }}
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.
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 }}
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. :)