Adding Google Analytics to AMP posts in Ghost
Ghost comes with AMP support, however there is no built in way to in the administration UI to add Google Analytics to your AMP theme. Fortunately, implementing this is relatively simple.
I noticed that out of the box, Ghost comes with AMP support (as has done since 2016), however there is no built in way to in the administration UI to add Google Analytics to your AMP theme. This means you will be missing out on a portion of your mobile traffic in your analytics. Not great.
Fortunately, implementing this is relatively simple.
Download the starter AMP page template
You can grab Ghost's start AMP page template from their Github repository. Place amp.hbs
into the root of your theme.
Add in the required Google Analytics code
There are 2 sections
In the <head>
section, near the end of it, place the Javascript include:
{{!-- Load amp-analytics --}}
<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
After the <body>
tag is opened add the following gtag
configuration section. You will need to replace the UA-XXXXXXX-X
with your own Google Analytics property ID.
{{!-- Configure analytics to use gtag --}}
<amp-analytics type="gtag" data-credentials="include">
<script type="application/json">
{
"vars" : {
"gtag_id": "UA-XXXXXXX-X",
"config" : {
"UA-XXXXXXX-X": { "groups": "default" }
}
}
}
</script>
</amp-analytics>
You will then need to upload your theme to your Ghost blog, to which is covered nicely in this blog post.
Verify your AMP posts are valid
Option #1 - Use your browser's console
Visit any AMP post and add on to the end to the end of the URL #development=1
this will trigger the AMP validator to run. If you open the console of your browser, you should see something like this:
If you see AMP validation successful.
then you know at least the theme is still valid.
Option #2 - Use a Chrome extension
Another option (if the console is not your friend) is to use the dedicated plugin for AMP validation. There is one for chrome that I am aware of.
Option #3 - Use a website
Likely the simplest option if you content has a valid public URL, visit https://search.google.com/test/amp and plug in your URL to your AMP post, and then see the results:
Verify Google Analytics is working
Next steps is verifying that the tracking is enabled, you can prove this in the Network
tab of your browser's console and filtering by google-analytics
, you should see a request to a URL that starts off like collect?v=1&_v=a1&ds=AMP&aip&_s=1...
You can also just go checkout the realtime view inside Google Analytics itself:
Further reading and extra for experts
For more advanced topics like tracking custom events, using a custom URL, please see the official documentation from Google on this.