Hack: Placing the Google Tag Manager in WordPress After the body Tag

This article was first posted by Yaniv Friedensohn at affectivia.com

http://www.affectivia.com/blog/placing-the-google-tag-manager-in-wordpress-after-the-body-tag/ (broken link)

In this post, I will show how to insert the Google Tag Manager in WordPress immediately after the opening <body> tag. The solution isn’t based on a child theme or JavaScript.

To implement this solution you will need to create a snippet using the Code Snippets plugin.

I call this solution “GTM Injection” (please replace GTM-XXXXXX with your Google Tag Manager container ID):

add_filter( 'body_class', 'gtm_add', 10000 );

function gtm_add( $classes ) {

$block = <<<'BLOCK'

<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<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=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script>
<!-- End Google Tag Manager -->

BLOCK;

$classes[] = '">' . $block . '<br style="display:none';      
return $classes;
}

This solution takes two fair assumption:

  1. The theme’s opening <body> tag ends with <?php body_class(); ?>.
    For most scenarios this should be the case as WordPress asks to implement the body_class() template tag when developing a theme, and from my experience and looking at WordPress twentytwelve – twentyfifteen themes – the opening body tag is <body <?php body_class(); ?>>.
  2. There isn’t any other plugin which filters the body_class hook and has a lower priority than ours (the default priority is 10 – ours is arbitrary set to 10000).
    Unlike the first assumption – perhaps we can eliminate this assumption by using the PHP_INT_MAX priority, $wp_filter global variable, or the plugins_loaded hook – these methods should be further investigated.

Therefore, please make sure that your Google Tag Manager is located and works properly after applying this solution. View your website source code and use the Google Tag Assistant Chrome extension accordingly.

Let me know if this solution works for you.

p.s. Iv’e reached Thomas Geiger, the creator of the popular DuracellTomi’s Google Tag Manager for WordPress regarding adding this solution to the plugin. Hopefully this feature could be implemented soon so that more people could easily place their Google Tag Manager in WordPress in the correct place.

Update: As of version 1.1, the DuracellTomi’s Google Tag Manager for WordPress plugin contains my solution!