How to Install Google Analytics on Your WordPress AMP Content
In the last post we talked about how to get AMP working in WordPress and how to get it optimized for the Accelerated Mobile Pages search results. Today we’re going to talk about how to get Google Analytics working on the AMP content. We’re huge GA fans, and if we’re not tracking the traffic for our site, we really wonder why we’re doing it in the first place.
Google recommends that you create a new property for your AMP pages. The analytics library for AMP doesn’t have all the capabilities of a full-scale GA snippet, so there would be a bit of apples and oranges if you put that traffic into your main account. Also, there’s not going to be much traffic shuttling between the two versions of your site. There will be no traffic going from the real site to the AMP templates, and any traffic coming off the /amp pages will have only one source: Google mobile search.
Just like the logo we did in the previous blog post, you’re going to insert the Google Analytics onto your page using hooks dropped into functions.php. The AMP guidelines only allow pre-vetted one-size fits all javascript, which means you can’t just drop the normal GA snippet into your head. You will add Google Analytics using the “amp-analytics” tag, which you customize to your account using JSON.
Which is to say, copy and paste the code below and replace the “UA-xxxxxxx” with the Google Analytics ID for your new property, and that should do the trick.
//////////////adding analytics to AMP/////////// add_action( 'amp_post_template_head', 'xyz_amp_add_analytics_library' ); add_action( 'amp_post_template_footer', 'xyz_amp_add_analytics' ); function xyz_amp_add_analytics_library( $amp_template ) { $post_id = $amp_template->get( 'post_id' ); ?> <script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script> <?php } function xyz_amp_add_analytics( $amp_template ) { $post_id = $amp_template->get( 'post_id' ); // see https://github.com/ampproject/amphtml/blob/master/extensions/amp-analytics/amp-analytics.md for more on amp-analytics ?> <amp-analytics type="googleanalytics" id="analytics1"> <script type="application/json"> { "vars": { "account": "UA-xxxxxxx" }, "triggers": { "trackPageview": { "on": "visible", "request": "pageview" } } } </script> </amp-analytics> <?php } /////////////end adding AMP analytics////////////////
I haven’t been seeing the GA AMP tag showing up in the Tag Assistant extension, so you will need to look at this property through the real-time viewer to see if it’s actually tracking.
Leave a Reply
Want to join the discussion?Feel free to contribute!