PHP Magento Tips

How To Setup Google Analytics ecommerce:addTransaction Tracking code on Magento

Rate this posting:

Google Analytics is a very powerful and free service offered by the company behind the most popular search engine on the Internet. Google Analytics gives its users a complete picture of traffic visiting a website as a whole, as well as its individual pages, and special features (like videos, pictures, or web forms). It can also break down traffic patterns to show the numbers of site visitors using computers versus smartphones versus tablets. Together, these tools make it possible for site owners to get a better picture of who they are actually attracting to their site and create content that is ideally targeted to that audience. Targeted content usually equates to better customer engagement, and that leads to more sales.

Default Magento Google Analytics Integration


By default, Magento has some Google Analytics functions built into it. While these are useful, they do require some setup and integration to work properly. Do the following to get things started:

1. Visit Google Analytics’ signup page by clicking here. Once you have signed up, make note of your Google Analytics account number. We will need this number in later steps.

2. Sign into your Magento store’s backend. Once you are logged-in, go to
System-> Configuration-> Sales-> Google API

3. Find the "Enable" dropdown menu and select "Yes". Enter your account number in the appropriate field and click "Save config"

For Magento’s official instructions on implementing the default Google Analytics integration tools, click here.

Here is how you do it:

1. Create a new ga.phtml file, or copy it from the base folder, and place it in your theme folder. The path to the theme folder should look similar to this:


2. Next, you will add the appropriate code to the file you just created. If you copied and pasted the ga.phtml file, then you will need to delete all of the code it contains and substitute the following:

<?php if (!Mage::helper('core/cookie')->isUserNotAllowSaveCookie()): ?>
<?php $accountId = Mage::getStoreConfig(Mage_GoogleAnalytics_Helper_Data::XML_PATH_ACCOUNT) ?>
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//','ga'); 
<?php echo $this->_getPageTrackingCode($accountId) ?>
<?php echo $this->_getOrdersTrackingCode() ?>
<?php endif; ?>

3. Next, we will need to override the Google Analytics Block. If you are new to Magento, then the simplest way to accomplish this will be to cut and paste this block into the “app/code/local” folder. More advanced users will recognize that this is not the best way to override Blocks, but it is the simplest approach.

Copy the content of this file:


Now create this new file in the "local" folder:


4. In this file, we will need to replace two functions with the following code:

protected function _getPageTrackingCode($accountId) {
    $pageName = trim($this->getPageName()); $optPageURL = '';
    if ($pageName && preg_match('/^/.*/i', $pageName)) {
         $optPageURL = ", '{$this->jsQuoteEscape($pageName)}'";
    $hostName = $_SERVER['SERVER_NAME']; return " ga('create', '".$this->jsQuoteEscape($accountId)."', 'auto'); ga('send', 'pageview' ".$optPageURL."); ";

and this

protected function _getOrdersTrackingCode() {
    $orderIds = $this->getOrderIds();
    if (empty($orderIds) || !is_array($orderIds))
    { return; }
    $collection = Mage::getResourceModel('sales/order_collection') ->addFieldToFilter('entity_id', array('in' => $orderIds)) ;
    $result = array("ga('require', 'ecommerce', 'ecommerce.js');");
    foreach ($collection as $order) {
     if ($order->getIsVirtual()) {
        $address = $order->getBillingAddress();
     } else {
        $address = $order->getShippingAddress();
    $result[] = "ga('ecommerce:addTransaction', { id: '".$order->getIncrementId()."',affiliation: '".$this->jsQuoteEscape(Mage::app()->getStore()->getFrontendName())."',revenue: '".$order->getBaseGrandTotal()."',shipping: '".$order->getBaseShippingAmount()."',tax: '".$order->getBaseTaxAmount()."'});";foreach ($order->getAllVisibleItems() as $item) { $result[] = " ga('ecommerce:addItem', { id: '".$order->getIncrementId()."',sku: '".$this->jsQuoteEscape($item->getSku())."',name: '".$this->jsQuoteEscape($item->getName())."',category: '',price: '".$item->getBasePrice()."',quantity: '".$item->getQtyOrdered()."'});";}
    $result[] = "ga('ecommerce:send');";
    return implode("\n", $result);

That’s all it takes. If you followed these steps, and everything went according to plan, then your Magento site should be fully integrated with Google’s Universal Analytics tracking code.
Tag : Magento
0 Comments On "How To Setup Google Analytics ecommerce:addTransaction Tracking code on Magento"

Back To Top