How to add Google Tag Manager to Magento 2?

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> <!-- GTM code -->
# File: Theme_Vendor/Theme_Name/Magento_Theme/templates/html/gtm_body.phtml

</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="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <referenceContainer name="head.additional">
            <block class="Magento\Framework\View\Element\Template" name="gtm.head" before="-" template="Magento_Theme::html/gtm_head.phtml" />
        <referenceContainer name="after.body.start">
            <block class="Magento\Framework\View\Element\Template" name="gtm.body" before="-" template="Magento_Theme::html/gtm_body.phtml" />

And that is it 🙂


  1. 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?


Leave a Reply

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