Blog post with slightly more detail can be found here. If you want to just get to it, read on.
I (very) recently decided to reimplement GA in my site, and found that existing implementation in Hugo was not compatible with GA4's new Measurement ID. This is an easy way to drop your Measurement ID into your site. I'm not going to go into how to sign up for GA.
This implementation requires that you create a site parameter for analytics, create a partial, and call the partial. I tweaked the names of the parameters and files so they didn't collide with the built-in hugo code.
Place the GoogleAnalyicsID (Measurement ID) in config.toml
within [params]
.
# Google Analytics 4
googleAnalyticsID = "G-00000XXXXX"
Create the partial, analytics-gtag.html
, and place it in /layouts/partials
. Code below.
Call the partial just after the <head>
tag in /layouts/_default/baseof.html
.
<head>
{{ if .Site.Params.GoogleAnalyticsID }}
{{ partial "analytics-gtag.html" . }}
{{ end }}
...
</head>
That's it. It appears that this will be fixed in gohugo shortly, but for now this is a serviceable workaround.
I guess this might depend on the theme as well.
For example, as I'm using Clarify theme, when I was trying to refer to the hack @zjeaton provides, I realized that, after checking out the code Clarify theme has, there is no such a need at all to make any further change: I just updated the param of
ga_analytics = "G-XXXXXX"
and it worked perfectly fine with GA4's MEASUREMENT ID.For your convenience, I'd paste the the partial that the theme provides, as file of
layout/partials/analytics.html
: