This post will show you how to integrate Google Analytics to your Hexo blog.

1) The easy way. When your theme already supports Google Analytics.

If you are lucky, your theme already support Google Analytics. This is the case for the default theme and Light, the theme I started with.

Grab your site’s Google Analytics tracking ID. It should look something like UA-83746351-2

Then go to your theme’s main _config.yml and look for a property called google_analytics. Fill in your tracking ID.

1
google_analytics: UA-83746351-2

Google Analytics has been added to your site !

2) The not so difficult way. When you have to implement the tracking code yourself.

Following 1), prepare your Google Analytics tracking ID and add the following property to your theme’s _config.yml:

1
google_analytics: UA-83746351-2

Once this is done, let’s add the Analytics code to each page.

Create a new google_analytics.ejs file with the following code: (I am using EJS so adapt the code to the templating engine you are using)

1
2
3
4
5
6
7
8
9
10
11
12
<% if (theme.google_analytics){ %>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '<%= theme.google_analytics %>', 'auto');
ga('send', 'pageview');
</script>
<% } %>

This code is the Universal Analytics tracking code with a parameterized tracking ID.

Integrate this template to your theme so that it is included in the <head> tag of each page once the site is generated. Done !

Happy analyzing !