Google Tag Manager on WordPress

I was talking to a friend the other day and he mentioned to me he was using Google Tag Manager at his job and told me I should check it out, so I did. If you don’t know what Google Tag Manager is yet, it is as follows:

Google Tag Manager helps manage all of the different included js scripts or other tags in the head of the HTML file for your website. So for example, if you wanted to install Google Analytics on a website, you would have to grab the code they give you and paste it into your website’s HTML code. Which for me it isn’t a problem since I’ve been doing web development for some time now, many people would have no idea how to do it, or even not have access to it in the case of a small business with a webmaster.
So Google Tag Manager is just a single included js script for your site which allows you to use the tag manager dashboard to add or remove different scripts. So if you wanted to add google analytics, you wouldn’t need to ssh into your site then add it to some random php file, which is the case for my WordPress site. All you would have to do is log into the GTM dashboard and add it there, saving a ton of time and struggle, and money since the webmaster isn’t needed anymore.

To add it to a WordPress website, you would have to create an account and get the HTML code it gives you. Go to Admin -> Install Google Tag Manager to find it. Then ssh into your server ssh xxx.xxx.xxx.xxx, find the theme directory cd /var/www/html/wp-content/themes/twentyseventeen/, replacing twentyseventeen with whichever theme you are using. Then to the file functions.php, add the head code (yours will be a bit different)

/**
 * Google Tag Manager
 */
function google_tag_manager() {
    echo '<!-- 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-5P8Q84M");</script>
<!-- End Google Tag Manager -->';
}
add_action( 'wp_head', 'google_tag_manager' );

and inside header.php add

<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5P8Q84M"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->

And again, yours will be a bit different.

Now GTM should be loaded on your site and you should be able to go on to their dashboard and start adding tags at will.

Leave a Reply

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