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(); } $data['amp_component_scripts']['amp-analytics']='https://cdn.ampproject.org/v0/amp-analytics-0.1.js'; } 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"> <?php 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', ) ), ) ); ?> </script> </amp-analytics> <?php } }
And that’s it!
Thanks for solution! 🙂
thank but bit confusing you can also try on amp for wp plugin