Today I am explaining, how you can implement 3rd party services such as Google Analytics, Facebook Pixel or other tracking services in Magento. The reason why I am doing it is because for some reason it is still popular to put JavaScript code directly in theme files, such as page.phtml, success.phtml or footer.phtml. It might be a quick solution, but in most cases very difficult to maintain. With Magento you can easily create blocks which allows you to place the tracking codes by using layout handles without modifying any theme file.
Here is one example that you can easily adapt for other purposes.
1. Create a custom .phtml file
Go to your template folder ./app/design/frontend/{package}/default/template/ and create a new folder custom. Inside the custom folder create a file my_code.phtml and put all your JavaScript code in there.
|
<script type="text/javascript"> ... </script> |
2. Create or edit your local.xml file
Create or edit your existing local.xml file which should be located in ./app/design/frontend/{package}/default/layout/local.xml.
|
<?xml version="1.0"?> <layout version="0.1.0"> <default> ... </default> </layout> |
Inside of the <default> handle you have to place the following <reference>.
|
<?xml version="1.0"?> <layout version="0.1.0"> <default> <reference name="after_body_start"> <block type="core/template" name="my_code" template="custom/my_code.phtml" /> </reference> </default> </layout> |
With the attribute name before_body_end and after_body_start you can define the position inside of the <body>. The <default> layout handle is present in every page request and will add your JavaScript code on all pages. You can use other layout handles such as <checkout_onepage_success> to add your JavaScript code only on the checkout success page.
That’s it. If you clear the cache, you should see the content of my_code.phtml in your HTML code.
3. Pass data to your block
You may need some custom data in your block, such as Google Analytics Account ID or other values for a proper tracking. Those data, you can add to your block with setData.
|
<block type="core/template" name="my_code" template="custom/my_code.phtml"> <action method="setData"> <key>account_id</key> <value>1234567</value> </action> <action method="setData"> <key>track</key> <value>CheckoutSuccess</value> </action> </block> |
Use getData to receive the values.
|
<script> <?php echo $this->getData('account_id'); ?> <?php echo $this->getData('track'); ?> </script> |