Add Google Analytics tracking to WordPress Accelerated Mobile Pages (AMP) posts

Automattic released a WordPress plugin that allows to automatically publish versions of your posts in AMP.

Were at Webdados we’ve implemented this plugin in two publishing websites of our own, and needed to track visitors of these pages.


Google Analytics by Yoast, and other GA plugins, will most certainly add AMP support to their plugins, but until they do, we’ve enabled Google Analytics on our AMP pages following the simple steps bellow.

UPDATE: Yoast has now added Google Analytics support on AMP with it’s “Yoast SEO AMP Glue Plugin”.

Use your (child) theme functions.php or a custom plugin

Never, ever, mess around with the AMP (or any other) plugin files. We’ll not get into details on why, because if you’re reading this post you are most certainly an advanced user and you (should) know the reason.

Add the necessary Google Analytics extended component to the <head> section


add_filter( 'amp_post_template_data', 'my_amp_post_template_data' );
function my_amp_post_template_data($data) {
 $data[ 'site_icon_url' ] = get_stylesheet_directory_uri() . '/images/icons/icon-32x32.png';
 if ( !current_user_can('manage_options') ) { //No Analytics for admin
  //Google Analytics
  if ( !isset($data['amp_component_scripts']) ) {
   $data['amp_component_scripts'] = array();
 return $data;

As you can see, we’ve also used the amp_post_template_data filter to change the site icon 😉

Add the necessary Google Analytics element to the footer of your posts


add_action( 'amp_post_template_footer', 'my_amp_post_template_footer' );
function my_amp_post_template_footer($amp_template) {
 if ( !current_user_can('manage_options') ) { //No Analytics for admin
  <amp-analytics type="googleanalytics" id="analytics1">
   <script type="application/json">
    echo json_encode( array(
     'vars' => array(
      'account' => 'UA-xxxxxx-xx', //Your Google Analytics Property Tracking ID here (duh)
     'triggers' => array(
      'trackPageview' => array(
       'on' => 'visible',
       'request' => 'pageview',
    ) );


And that’s it!

5 comentários a Add Google Analytics tracking to WordPress Accelerated Mobile Pages (AMP) posts

  1. Makabe 2016-02-27 às 10:04 #

    Thanks for solution! 🙂

  2. raju ginne 2017-04-23 às 16:08 #

    thank but bit confusing you can also try on amp for wp plugin


  1. AMP up your Wordpress enabled sites in minutes - VScripts - 2016-03-13

    […] is a way to do this via hooks and filters but unless you have a good reason to hard-code this, using the PageFrog plugins make a lot more […]

  2. Плагины WordPress AMP — Accelerated Mobile Pages | Портал Seoxa - 2016-09-11

    […] можно сделать с помощью разных хуков и фильтров, прописать весь код самостоятельно или прибегнуть к […]

  3. Google Analytics Tracking zu WordPress Accelerated Mobile Pages (AMP) hinzufügen › Gdgts - 2016-11-06

    […] von Webdados helfen hier […]

Deixe um comentário