Skip to content

Instantly share code, notes, and snippets.

@mbrughi
Created August 11, 2021 14:39
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 mbrughi/1019b733180c39307c33a752024529e2 to your computer and use it in GitHub Desktop.
Save mbrughi/1019b733180c39307c33a752024529e2 to your computer and use it in GitHub Desktop.
Wordpress snippet code to add Google Tag Manager (please change only GTM-WB6FPJN with your GTM Code).
/*
* Insert Google Analytics Code
* 99 to right before </head> tag
*/
function hook_javascript() {
?>
<!-- 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-WB6FPJN');</script>
<!-- End Google Tag Manager -->
<?php
}
add_action('wp_head', 'hook_javascript', 99);
// Add Google Tag code which is supposed to be placed after opening body tag.
add_action( 'wp_body_open', 'mb_add_custom_body_open_code' );
function mb_add_custom_body_open_code() {
echo '<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WB6FPJN"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
'.PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment