為 Hexo Blog 加上 Google analytics

前言

建立部落格後,可以透過加入 GA 來了解的文章的人氣狀況,但目前網路上的版本很多,有的也無法正常執行,所以整理了目前可以使用的流程。

流程

  1. 使用 NPM 的方式安裝 Theme
  2. 複製 config
1
cp node_modules/hexo-theme-next/_config.yml _config.next.yml
  1. 啟用 head,將原本的註解移除掉

_config.next.yml

1
2
3
4
5
6
7
8
9
10
11
custom_file_path:
head: source/_data/head.njk
#header: source/_data/header.njk
#sidebar: source/_data/sidebar.njk
#postMeta: source/_data/post-meta.njk
#postBodyEnd: source/_data/post-body-end.njk
#footer: source/_data/footer.njk
#bodyEnd: source/_data/body-end.njk
#variable: source/_data/variables.styl
#mixin: source/_data/mixins.styl
#style: source/_data/styles.styl
  1. 將 GA 相關程式碼貼到檔案中

source/_data/head.njk

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

gtag('config', 'G-XXXXX');
</script>

Reference

https://theme-next.js.org/docs/advanced-settings/custom-files.html