Skip to content

Instantly share code, notes, and snippets.

@WordBits
Created September 30, 2018 03:08
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 WordBits/74ea07d9c457a0948f03ca95bc2c6b78 to your computer and use it in GitHub Desktop.
Save WordBits/74ea07d9c457a0948f03ca95bc2c6b78 to your computer and use it in GitHub Desktop.
This snippet allows you to add GTM (or other) code snippets to a site without having to guess which header/footer files are bing used by a theme. Convenience snippet for use in child themes where the parent theme uses multiple header/page/footer files. Instead of figuring out by trial and error which one is being used, simply drop this code into…
<?php
// Download this snippet as a plugin and more at: https://wordbits.io/snippet/add-gtm-ga-other-code-to-site-header-and-or-body/
// Created by: Fernando Ayala
?>
<?php
function hook_insert_in_header() {
/* Example for Google Tag Manager
Simply replace the code snippet below with the snippet that needs to be
in the header of your site.
*/
?>
<!-- example for 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','xxxxxxxxxxxx');</script>
<!-- End Google Tag Manager -->
<?php
}
add_action('wp_head', 'hook_insert_in_head', 20);
function hook_insert_in_footer() {
/* example for Google Tag Manager
Simply replace the code snippet below with the snippet that needs to be
in the footer of your site.
*/
?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=xxxxxxxxxxxx"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php }
add_action( 'wp_footer', 'hook_insert_in_footer', 20 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment