Hugo 添加 Google Analytics

(2024.08.22)

修改 config.yaml 配置文件,在文件末尾添加以下代码

1
services: googleAnalytics: ID: G-JQN2M0MC5N # Enable Google Analytics by entering your tracking id

在 Hugo 站点根目录下新建模板文件(./layouts/_internal/google_analytics.html)并添加如下代码:

1
2
3
4
5
6
7
8
9
    <!-- Global Site Tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id={{ .Site.GoogleAnalytics }}"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', '{{ .Site.GoogleAnalytics }}');
    </script>
本博客已稳定运行