Reputation: 23
I want to add Google Tag Manager to Magento but i don't want to use a plugin for this, my question is what's best practice? i've read some on creating a module but also including the GTM inside the body tag, the problem is for me to find the file loading the body of every page.
Thanks
Upvotes: 0
Views: 3636
Reputation: 38
To add a script block (or anything else you may need) to every page is pretty simple as long as you are ok to edit your themes files. You can edit your page.xml file from within your theme.
magento\app\design\frontend\<YOUR_INTERFACE>\<YOUR_THEME>\layout\page.xml
Add a new block to the All Pages block. In this block you will find all the head scripts and css. Example below:
<default translate="label" module="page">
<label>All Pages</label>
<block type="page/html" name="root" output="toHtml" template="page/1column.phtml">
<block type="page/html_head" name="head" as="head">
<action method="addJs"><script>prototype/prototype.js</script></action>
<block type="page/js_cookie" name="js_cookies" template="page/js/cookie.phtml"/>
<action method="addItem"><type>skin_js</type><name>js/app.js</name></action>
<action method="addItem"><type>skin_js</type><name>js/script.min.js</name></action>
<!-- Add stylesheets with media queries for use by modern browsers -->
<action method="addItem"><type>skin_css</type><name>css/styles.css</name><params/></action>
<!-- Sets viewport meta tag using text block -->
<block type="core/text" name="head.viewport">
<action method="setText"><text><![CDATA[<meta name="viewport" content="initial-scale=1.0, width=device-width, maximum-scale=1, user-scalable=no" />]]> </text></action>
</block>
</block>
<!-- add GTM block here -->
<block type="core/template" name="gtm" as="after_body_start" template="page/html/gtm.phtml" />
</block>
<block type="core/profiler" output="toHtml" name="core_profiler"/>
</default>
The block to add will be something like this (see block in place in code above)
<block type="core/template" name="gtm" as="after_body_start" template="page/html/gtm.phtml" />
You then just need to create a new file in your theme:
magento\app\design\frontend\<YOUR_INTERFACE>\<YOUR_THEME>\template\page\html\gtm.phtml
Paste your GTM code snippet in the gtm.phtml file.
In your page template, for example page/1column.phtml you will find a snippet of php just after the opening body tag:
<?php echo $this->getChildHtml('after_body_start') ?>
This is where your GTM code will be added on all pages.
Upvotes: 1