How to add Google Tag Manager to Magento 2?

Don’t confuse Google Tag Manager (GTM) with the latest version of Google Analytics, as it helps to set up the GA and any other code.
GTM relatively consists of 3 main parts:

  • Tag - Tag is a patch of code (more often it’s JavaScript) added to a page. 
  • Triggers - Trigger identifies when and where the tags are to be executed.
  • Variables - Variables receive and keep information used by tags and triggers.

The app eliminates the need to have deep knowledge in JavaScript and make everything manually. Instead of it, you can add a container tag (a custom-generated tracking code) to your website and add, change, debug tags, of course, if you have the appropriate user permissions. 

How to add Magento 2 Google Tag Manager?

You can easily add Google Tag Manager in Magento 2 without third-party extensions. All you need is to add the GTM code to your active theme. The GTM code is divided into two parts: script and noscript.
You need to put the GTM snippet into these two phtml templates for head and body:

// YourTheme/Magento_Theme/templates/html/gtm_head.phtml
<script>..</script> <!-- GTM code -->

// YourTheme/Magento_Theme/templates/html/gtm_body.phtml
<noscript>..</noscript> <!-- GTM code -->

 

To load the files correspondingly you should use the default .xml file:

<!-- YourTheme/Magento_Theme/layout/default.xml -->
<referenceContainer name="head.additional">
<block class="Magento\Framework\View\Element\Template" name="gtm.head" before="-" template="Magento_Theme::html/gtm_head.phtml" />
</referenceContainer>

<referenceContainer name="after.body.start">
<block class="Magento\Framework\View\Element\Template" name="gtm.body" before="-" template="Magento_Theme::html/gtm_body.phtml" />
</referenceContainer>

After GTM is added you can set up Google Analytics and other tools for tracking and reporting about website traffic.

If connecting 3rd-party extensions to your Magento 2 isn't really an option right now, check out this Advanced Reports extension: 20+ marketing reports, sales performance reports, real-time reports, create custom reports, customizable data grids.

How can we help you?

Didn’t you find the answer to your question? We are always happy to help you out.

© 2009-2021 Amasty. All Rights Reserved.