You can easily add GTM in you website without the need of any third-party extensions.
Although you can add GTM code snippet directly in the admin (Content > Design > Configuration
) you will not be able to add the noscript part right below the body tag.
To solve this problem you will need a bit more work and add the GTM code to your theme
The GTM code is divided into two parts: script
and noscript
. You must put each part of the GTM snippet into two different phtml
templates, one for head
and the other for body
:
# File: Theme_Vendor/Theme_Name/Magento_Theme/templates/html/gtm_head.phtml <script> .. </script> <!-- GTM code -->
# File: Theme_Vendor/Theme_Name/Magento_Theme/templates/html/gtm_body.phtml <noscript> .. </noscript> <!-- GTM code -->
You will know need to load these templates by changing the default layout file (default.xml
):
# File: Theme_Vendor/Theme_Name/Magento_Theme/layout/default.xml <?xml version="1.0"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <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> </body> </page>
And that is it 🙂
Hi there,
I don’t have this path “Magento_Theme/templates/html/” in my Magento 2.4.4C, meaning that in Magento_Theme folder I only have “layout” and “web”, but no “templates” folder. Is this a folder that you created on your own?
Thanks,
Alexx
Correct. If you do not have that folder you should create it