Skip to content

Instantly share code, notes, and snippets.

@dcavins
Created October 5, 2020 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcavins/e8ed9d0b85f6e7afd13ca20e20f099b9 to your computer and use it in GitHub Desktop.
Save dcavins/e8ed9d0b85f6e7afd13ca20e20f099b9 to your computer and use it in GitHub Desktop.
Add the Google Tag Manager snippets to a WordPress theme's `functions.php` file.
<?php
/**
* Add the Google tag manager script in the header.
*
* @since 1.0.0
*
*/
function prefix_add_google_tag_manager_script() {
if ( function_exists( 'wp_get_environment_type' )
&& 'production' !== wp_get_environment_type() ) {
?>
<!-- Google Tag Manager: Not loaded on dev environment. -->
<?php
return;
}
?>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{GTM_CONTAINER_ID}');</script>
<!-- End Google Tag Manager -->
<?php
// Add the action that creates the noscript version.
add_action( 'wp_body_open', 'prefix_add_google_tag_manager_noscript_tag' );
}
add_action( 'wp_head', 'prefix_add_google_tag_manager_script' );
/**
* Add the Google "noscript" tag immediately after the opening of the body element.
*
* @since 1.0.0
*
*/
function prefix_add_google_tag_manager_noscript_tag() {
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id={GTM_CONTAINER_ID}"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment