Home / Blog / E-Commerce / How to Setup Google Analytics on Magento (with code examples)
How to Setup Google Analytics on Magento (with code example)

How to Setup Google Analytics on Magento (with code examples)

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.
  1. Sign into your Magento store’s backend. Once you are logged-in, go to System-> Configuration-> Sales-> Google API.

Magento google analytics

  1. Find the “Enable” dropdown menu and select “Yes.” Enter your account number in the appropriate field and click “Save config.”

Magento google analytics setup

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

What is Google Universal Analytics?

Google recently upgraded its familiar Google Analytics platform to the new Google Universal Analytics. The upgrade added a number of new features, most of which are not important to this discussion, but which you can learn about by visiting Tthis page.

There are, however, two major improvements of note: multi-platform tracking and custom dimensions and metrics.

Multi-Platform tracking allows site owners to collect data relating to the device and operating system site visitors use when viewing a page. This will reveal whether the visitor is a Mac or Windows user, viewing your web pages on a computer or a mobile phone, and which web browser your visitors prefer to use.

Custom Dimensions and Metrics, on the other hand, allow you to create your own tools for tracking the sources and types of traffic visiting your website. Unlike previous versions of Google Analytics, Custom Dimensions and Metrics allow you to create exactly which things you want to track, best matching your unique needs to the tools available.

To learn more about Universal Analytics and how to get either a new setup/tracking code or upgrade an existing one, click here.

How to Upgrade to Universal Analytics on Your Magento Site

To take advantage of Google’s Universal Analytics tools you will need to change your Magento code to make it compatible with Universal Analytics. There are several ways to do this.

One method is to use a pre-packaged plugin. Many of these plugins are free and may work well for you. However, as with any one-size-fits-all software, these plugins may create conflicts or limited functionality. Still, some of these plugins can be quite useful for a site with the right configuration. One plugin we recommend is Fooman Google Analytics+. This plugin is well documented and fairly easy to install.

The better approach is to actually write the code required to implement Google Universal Analytics. It is not terribly difficult, although there are several ways to implement it. What we present below is a simplified method of accomplishing this goal that should work for most sites. Nevertheless, for a better, deeper integration with your site, feel free to contact us to arrange for some custom coding.

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:
/app/design/frontend/Your_Theme/default/template/googleanalytics/ga.phtml
  1. 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) ?>
<!-- BEGIN GOOGLE ANALYTICS CODEs -->
<script type="text/javascript"> //<![CDATA[ (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','//www.google-analytics.com/analytics.js','ga'); <?php echo $this->_getPageTrackingCode($accountId) ?>
<?php echo $this->_getOrdersTrackingCode() ?> //]]>
</script>
<?php endif; ?>
  1. 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:

/app/code/core/Mage/GoogleAnalytics/Block/Ga.php

Now create this new file in the “local” folder:

app/code/local/Mage/GoogleAnalytics/Block/Ga.php
  1. 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(" // Transaction code... 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()."', // Transaction ID affiliation: '".$this->jsQuoteEscape(Mage::app()->getStore()->getFrontendName())."', // Affiliation or store name revenue: '".$order->getBaseGrandTotal()."', // Grand Total shipping: '".$order->getBaseShippingAmount()."', // Shipping cost tax: '".$order->getBaseTaxAmount()."', // Tax }); "; foreach ($order->getAllVisibleItems() as $item) { $result[] = " ga('ecommerce:addItem', { id: '".$order->getIncrementId()."', // Transaction ID. sku: '".$this->jsQuoteEscape($item->getSku())."', // SKU/code. name: '".$this->jsQuoteEscape($item->getName())."', // Product name. category: '', // Category or variation. there is no 'category' defined for the order item price: '".$item->getBasePrice()."', // Unit price. quantity: '".$item->getQtyOrdered()."' // Quantity. }); "; }
$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. If you hit any hiccups, feel free to contact Absolute Web Services today to get the expert advice and help you need to get your site running perfectly smooth and with full Google Universal Analytics integration.