Magento – Add Google Tag Manager to Magento 2

google-tag-managermagento2

I'm using magento 2 and I'm trying to add the Google Tag Manager code (noscript and script parts) to my magento 2 installation , what's the best way to do it ?

I found this module to do it
https://github.com/magepal/magento2-googletagmanager

But once I enable it and add the code , when I go to my website I get a 404 error

The page you requested was not found, and we have a fine guess why

And is the same even if i try to go to the admin panel , the only way to revert this is to disable the module from the database.

Does anyone has any idea why it acts like that ?

Best Answer

If you want to add Google Tag Manager without creating a module, you can add the gtm code from your active theme.

You can have two phtml templates to include the GTM snippet that needs to go to 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 -->

You can use the default.xml file to load the above files.

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

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