Quantcast
Viewing all articles
Browse latest Browse all 6

Google Tag Manager on WordPress

Well, a WordPress site that you host yourself is not perhaps the kind of site where you benefit most from using Google Tag Manager (GTM). However, it is a great way to learn and try out GTM without the risk of negative impact on your e-commerce site. In order to fully utilize GTM for Google Analytics, you need a data layer. WordPress doesn't provide a data layer as a JSON-array as default so you have to create one (I couldn't find any plugin at the time writing). I could probably have written a plugin for this but I didn't have the time to figure out how.

First, find the functions.php in your theme. Add the following function in it:

if ( !function_exists( 'before_tag_manager' ) ) {
function before_tag_manager() { 
global $query_string, $post;
$post_id = $post->ID;
 if( have_posts() ) : 
 while( have_posts() ) : the_post();
 $output[]= array( 'title' => get_the_title(), 'date' => get_the_date());
 endwhile;
 endif;
 if(isset($output)){ 
 echo "<script>dataLayer =" . json_encode($output) . "</script>";
 }
 }
} // endif

Then you need to add the function call to your theme's header template (usually header.php). Locate the body start tag and add the function call immediately after that, then add the GTM-script:

</head>
<body <?php body_class(); ?>>
<?php before_tag_manager(); ?>
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-9Q8B"
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','<YOUR CONTAINER ID>');</script>
<!-- End Google Tag Manager -->

If you want to play with other variables in the data layer than "title" and "date", you can easily add context by using the built in template tags in wordpress and put them in the $output variable in the before_tag_manager function call. If you view the source code on one of your blog posts you will now see a dataLayer containing both the "title" and "date" of the post. The variables are now easily accessed from the Google Tag Manager Macros as Data Layer variables.

Image may be NSFW.
Clik here to view.

Google Tag Manager - Data Layer


Viewing all articles
Browse latest Browse all 6

Trending Articles