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 Google Tag Manager in Magento 2?

You can easily add GTM 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.

Rate the answer?