Skip to content

Instantly share code, notes, and snippets.

@JonatasAmaral
Forked from westonruter/amp-google-tag-manager.php
Last active November 18, 2022 21:12
Show Gist options
  • Save JonatasAmaral/c871406c6fab056335d788d8c0923eb3 to your computer and use it in GitHub Desktop.
Save JonatasAmaral/c871406c6fab056335d788d8c0923eb3 to your computer and use it in GitHub Desktop.
Plugin demonstrating how to inject GTM for the AMP plugin, in response to support forum topic: https://wordpress.org/support/topic/amp-with-google-tag-manager/
<?php
/**
* Plugin Name: AMP Google Tag Manager
*
* @package AMP_Google_Tag_Manager
* @author Weston Ruter, Google
* @license GPL-2.0-or-later
* @copyright 2019 Google Inc.
*
* @wordpress-plugin
* Plugin Name: AMP Google Tag Manager
* Description: Add Google Tag Manager (GTM) to an AMP page in WordPress. Including Web Stories pages from the plugin: https://wordpress.org/plugins/web-stories/
* Plugin URI: https://gist.github.com/JonatasAmaral/c871406c6fab056335d788d8c0923eb3
* Original Plugin URI: https://gist.github.com/westonruter/2ea25735be279b88c6f0946629d0240c
* Version: 0.2.1
* Author: Weston Ruter, Google
* Author URI: https://weston.ruter.net/
* License: GNU General Public License v2 (or later)
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
* Gist Plugin URI: https://gist.github.com/JonatasAmaral/c871406c6fab056335d788d8c0923eb3
* Original Gist Plugin URI: https://gist.github.com/JonatasAmaral/c871406c6fab056335d788d8c0923eb3
*/
namespace AMP_Google_Tag_Manager;
/** 👇👇👇 This must be populated here with your appropriate value. Or defined elsewhere (preferably in `wp-config.php`) */
define('AMP_GTM_CONTAINER_ID', '______________________');
/**
* Print amp-analytics.
*/
function print_component() {
printf(
'<amp-analytics config="https://www.googletagmanager.com/amp.json?id=%s" data-credentials="include"></amp-analytics>',
esc_attr( AMP_GTM_CONTAINER_ID )
);
}
/** _`is_amp_endpoint` deprecated in favor of `amp_is_request`[see here](https://amp-wp.org/reference/function/is_amp_endpoint/)_ */
$add_amp_gtm = function () {
if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
print_component();
}
};
add_action('wp_footer', $add_amp_gtm);
// include Web Stories pages: https://wordpress.org/plugins/web-stories/
add_action('web_stories_print_analytics', $add_amp_gtm);
// Classic mode.
add_filter(
'amp_post_template_data',
function( $data ) {
$data['amp_component_scripts'] = array_merge(
$data['amp_component_scripts'],
array(
'amp-analytics' => true,
)
);
return $data;
}
);
add_action( 'amp_post_template_footer', __NAMESPACE__ . '\print_component' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment