This tutorial demonstrates various ways to install JSON Google Analytics tracking code on your website built with AMP & WordPress.
{ "vars": { "account": "UA-XXXXXXXX-Y" }, "triggers": { "trackPageview": { "on": "visible", "request": "pageview" } } }
This is the simplest code to install Google Analytics on AMP website. If you need a more advanced solution, perhaps I’ll write an article about that later.
Like a regular Google Analytics implementation, AMP Analytics requires Your Google Analytics Tracking ID to function. If you know where to find it – skip this segment, but in case you don’t follow through. We have to learn building this thing from the very bottom. ain’t we?
First, navigate to your Admin Settings of Google Analytics and under the property select Tracking info > Tracking Code. You’ll find your Tracking ID here in format “UA-XXXXXXXX-YY”.
Implementing AMP Analytics on your website is one of those things, which could be done within minutes, but might be frustrating without the right knowledge. Once you have the right JSON code to install AMP Google Analytics code on your website this could be done in several ways.
Installing AMP Analytics JSON Code via AMP for WordPress plugin is probably the most convenient way to do it since most of AMP WordPress sites will have this official AMP plugin installed anyway. All you need to paste the code to Analytics section of AMP for WordPress plugin. For the entry type I gave name of “googleanalytics”.
In order to install AMP analytics JSON code using Yoast SEO, the plugin alone won’t be enough. Glue for Yoast SEO & AMP plugin has to be installed as well. After installing all the required plugins, simply go to Yoast SEO Settings > AMP and enter the code under Analytics tab.
If you don’t want to use either AMP for WordPress or Yoast SEO plugin, you can add the code directly to your theme. Though I wouldn’t recommend it if you don’t know what you are doing. Your website might break, so it is recommended to make a backup before proceeding.
The code below uses wp_head
action to import the required Google Analytics code to your WordPress AMP website.
add_action('wp_head', 'ampirecity_add_ga_code'); function ampirecity_add_ga_code(){ ?> <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script> <amp-analytics type="gtag" data-credentials="include"> <script type="application/json"> { "vars": { "account": "UA-XXXXXXXX-YY" }, "triggers": { "trackPageview": { "on": "visible", "request": "pageview" } } } </script> <?php };
Change “UA-XXXXXXXX-YY” to your Google Analytics ID and enter the code above to your functions.php
file. The easiest way to do so is with native WordPress theme editor. It is located under Appearance settings in the admin menu.
Note that if you are using any of AMP plugins, it is not required to add amp-analytics-0.1.js
because the plugin will do that for you.
Originally posted on 4/15/2020
WordPress 5.4
AMP 1.5.2
Yoast SEO 13.5