How to add Google Tag Manager code in Genesis

Posted on Leave a comment
5/5 - (317 votes)

In my Facebook group a user asks:

Can someone point me to the technique for adding Google Tags or “google tag manager” to a WordPress site? It needs to go beneath the tag of the header file. I’m uncertain how to proceed. Thanks.

To implement Google Tag Manager in your Genesis site, we need to add a piece of code in <head> and another in <body>.

Add the following in your child theme’s functions.php

// Add Google Tag Manager code in <head>
add_action( 'wp_head', 'sk_google_tag_manager1' );
function sk_google_tag_manager1() { ?>
<!-- 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-XXXXXX');</script>
<!-- End Google Tag Manager -->
<?php }

// Add Google Tag Manager code immediately below opening <body> tag
add_action( 'genesis_before', 'sk_google_tag_manager2' );
function sk_google_tag_manager2() { ?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXX"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php }

Replace the code inside the above functions with the snippets provided by Google in the Tag Manager interface or replace GTM-XXXXXX with your container ID.

Leave a Reply

Your email address will not be published. Required fields are marked *