Enable AMP Analytics using a custom WordPress plugin

I’ve recently enabled support for Facebook Instant Articles, Google AMP, and Apple News on this blog following this enlightening article.

It wasn’t exactly plain sailing; AMP needs a logo, and a featured image set for every article (both of which must be above a minimum size); the Instant Articles plugin has a feed url which my feedburner plugin breaks; Apple News needs some real tweaking, but still strips out code blocks from posts.

However, I also wanted to get my AMP plugin hooked up with my Google Analytics tracking. Luckily, the plugin from Automattic has support for this, but I needed to implement the analytics configuration using a custom theme or a custom plugin.

I’m not a PHP developer, let alone a WordPress developer, so this doesn’t come naturally to me! Please bear with me..

Following the instructions on the Automattic AMP plugin github page, I decided to create a custom plugin in my /wp-content/plugins directory; I created a new dir – amp-analytics – and put the following in a amp-analytics.php file:

<?php
/*
Plugin Name: amp-analytics
Plugin URI:  https://robinosborne.co.uk/
Description: adding analytics into amp
Version:     20160927
Author:      Robin Osborne
Author URI:  https://robinosborne.co.uk/
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: wporg
Domain Path: /languages

*/

add_filter( 'amp_post_template_analytics', 'xyz_amp_add_custom_analytics' );
function xyz_amp_add_custom_analytics( $analytics ) {
    if ( ! is_array( $analytics ) ) {
        $analytics = array();
    }

    // https://developers.google.com/analytics/devguides/collection/amp-analytics/
    $analytics['xyz-googleanalytics'] = array(
        'type' => 'googleanalytics',
        'attributes' => array(
            // 'data-credentials' => 'include',
        ),
        'config_data' => array(
            'vars' => array(
                'account' => "UA-000000-0"
            ),
            'triggers' => array(
                'trackPageview' => array(
                    'on' => 'visible',
                    'request' => 'pageview',
                ),
            ),
        ),
    );

    return $analytics;
}

?>

This resulted in a new a plugin appearing in my WordPress dashboard:

my custom amp-analytics plugin appearing

Once activated, I visited an “amp” version of my most recent article and viewed the source to find the GA content nicely rendered for me:

amp analytics in the page source

Hurrah! WordPress rocks!

Leave a Reply

Your email address will not be published. Required fields are marked *