Magento Google Analytics fix

Featured Image

If you updated to latest Magento or version you may notice that Google Analytics implementation is broken. Here are few easy instructions how to fix this.

Navigate to and open app/code/core/Mage/GoogleAnalytics/Block/Ga.php and add this on line 179

var _gaq = _gaq || [];

Since this bug is already reported and fix can be seen on latest official svn, I don’t see any harm in modifying core files in this particular situation.

As Magento Team said, changes will be included in next stable release.

About Ivan Weiler

Technical Educator and Consultant

Ivan is a Technical Educator and Consultant. He gained lots of experience managing some of the most complex Magento projects we had at Inchoo.

Read more posts by Ivan / Visit Ivan's profile


  1. Hi, All

    If someone also wants to use the new GoogleAnalytics-Module inside Magento v1.4.0.1 – please do not only copy the code from the Magento v1.5-trunk or the v1.6-trunk (which are nearly the same) but also apply this patch to get a valid backport:

    Index: brodering/app/code/core/Mage/GoogleAnalytics/Model/Observer.php
    --- brodering/app/code/core/Mage/GoogleAnalytics/Model/Observer.php	(revision 15)
    +++ brodering/app/code/core/Mage/GoogleAnalytics/Model/Observer.php	(revision )
    @@ -57,13 +57,14 @@
         public function setGoogleAnalyticsOnOrderSuccessPageView(Varien_Event_Observer $observer)
    -        $orderIds = $observer->getEvent()->getOrderIds();
    -        if (empty($orderIds) || !is_array($orderIds)) {
    +        $quoteId = Mage::getSingleton('checkout/session')->getLastQuoteId();
    +        if (!$quoteId) {
     		$block = Mage::app()->getFrontController()->getAction()->getLayout()->getBlock('google_analytics');
    -        if ($block) {
    -            $block->setOrderIds($orderIds);
    +        if ($block instanceof Mage_Core_Block_Abstract) {
    +            $quote = Mage::getModel('sales/quote')->load($quoteId);
    +            $block->setQuote($quote);
    Index: brodering/app/code/core/Mage/GoogleAnalytics/Block/Ga.php
    --- brodering/app/code/core/Mage/GoogleAnalytics/Block/Ga.php	(revision 15)
    +++ brodering/app/code/core/Mage/GoogleAnalytics/Block/Ga.php	(revision )
    @@ -104,37 +104,33 @@
         protected function _getOrdersTrackingCode()
    -        $orderIds = $this->getOrderIds();
    -        if (empty($orderIds) || !is_array($orderIds)) {
    -            return;
    +        $order = $this->getQuote();
    +        if (!$order) {
    +            return '';
    -        $collection = Mage::getResourceModel('sales/order_collection')
    -            ->addFieldToFilter('entity_id', array('in' => $orderIds))
    -        ;
    -        $result = array();
    -        foreach ($collection as $order) {
    -            if ($order->getIsVirtual()) {
    -                $address = $order->getBillingAddress();
    -            } else {
    -                $address = $order->getShippingAddress();
    -            }
    -            $result[] = sprintf("_gaq.push(['_addTrans', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s']);",
    -                $order->getIncrementId(), Mage::app()->getStore()->getFrontendName(), $order->getBaseGrandTotal(),
    -                $order->getBaseTaxAmount(), $order->getBaseShippingAmount(),
    -                $this->jsQuoteEscape($address->getCity()),
    -                $this->jsQuoteEscape($address->getRegion()),
    -                $this->jsQuoteEscape($address->getCountry())
    -            );
    -            foreach ($order->getAllVisibleItems() as $item) {
    -                $result[] = sprintf("_gaq.push(['_addItem', '%s', '%s', '%s', '%s', '%s', '%s']);",
    -                    $order->getIncrementId(),
    -                    $this->jsQuoteEscape($item->getSku()), $this->jsQuoteEscape($item->getName()),
    -                    null, // there is no "category" defined for the order item
    -                    $item->getBasePrice(), $item->getQtyOrdered()
    -                );
    -            }
    -            $result[] = "_gaq.push(['_trackTrans']);";
    +        if ($order->getIsVirtual()) {
    +            $address = $order->getBillingAddress();
    +        } else {
    +            $address = $order->getShippingAddress();
    +        }
    +        $result[] = sprintf("_gaq.push(['_addTrans', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s']);",
    +            $order->getIncrementId(), Mage::app()->getStore()->getFrontendName(), $order->getBaseGrandTotal(),
    +            $order->getBaseTaxAmount(), $order->getBaseShippingAmount(),
    +            $this->jsQuoteEscape($address->getCity()),
    +            $this->jsQuoteEscape($address->getRegion()),
    +            $this->jsQuoteEscape($address->getCountry())
    +        );
    +        foreach ($order->getAllVisibleItems() as $item) {
    +            $result[] = sprintf("_gaq.push(['_addItem', '%s', '%s', '%s', '%s', '%s', '%s']);",
    +                $order->getIncrementId(),
    +                $this->jsQuoteEscape($item->getSku()), $this->jsQuoteEscape($item->getName()),
    +                null, // there is no "category" defined for the order item
    +                $item->getBasePrice(), $item->getQtyOrdered()
    +            );
    +        }
    +        $result[] = "_gaq.push(['_trackTrans']);";
    -        }
             return implode("\n", $result);
  2. In the magento-version several problems have been fixed during a refactoring of the module GoogleAnalytics.

    Now I’ll try to integrate the refactored module into Magento for this bug is not fixed. There are also several problems concerning the tracking of sales. Maybe these bugs will be fixed during the refactoring – I really hope this.

    Currently it seems as I just have to update this module – nothing else. It’d be great if it’d be like that.


  3. Lol. I don’t know if all three of these guys are wrong, but I’m reading the code on svn.magento and in the post as having a space after var . So the code is:

    var _gaq = _gaq || [];

  4. beware of the spelling mistake in the previous post:

    var_gaq = gaq || [];


    var_gagq = gaq || [];

  5. The code is

    var_gagq = gaq || [];

    Right? I have to squint to see it. I had the same problem as Eddie. I see 2 visitors a day, but I hope I have a few more in reality, hehe. I’ve inserted this fix, I’ll find out if it works in about 24 hours.

  6. could you please tell me the exact code to input and the path to the files needs to be altered..

    i am just very novice at this..
    help most appreciated

  7. @Tom – there’s also a new root node in page.xml: after_body_start – make sure you have that in your page.xml and in your layout templates (1column.phtml, etc)

  8. Hi

    I have added this code (as a matter of fact i just uploaded the new file to it’s location) , re saved the code on magento backend, but still I can’t see it’s not showing “Tracking Not Installed”

    any ideas?

  9. Thanks for the tip. I also found that I had the following missing in main page templates (.phtml)

    getChildHtml(‘after_body_start’) ?>

    If you templates don’t have that, then the code won’t get included at all.

  10. 2 Eddie and Mazzy

    My client have a magento store

    First, He used to have this store on joomla but later he migrated it to magento. Since he migrated the store Google Analytics stopped working for him.

    He is using magento version I know that there was some bug in GA code but i took updated GA code from SVN so that’s fine but still i am not able to make it work.

    Any help or questions would be appericated.

  11. Thanks so much for this fix. I was wondering why I went from 100+ visitors a day to 0 when I upgraded and figured out something was wrong with Magento’s implementation of GA.

  12. @mazzy: i had the issue BEFORE i installed the fix above. now 100% of the visits are being accounted for.

  13. 2 Eddie: I do have exactly the same issue. Unfortunately, I do not know the solution.
    There are some “visits” showing up in GA – strange thing is that I have more orders than visits and ZERO “page views”.. very strange.. Correct GA code is showing on every page on the web…

  14. weirdly enough is that GA did not report ZERO pageviews. It dropped by 95%, but it wasnt zeroed out. Did anyone else experience this, and if yes, whats the explanation!?

  15. Good stuff! Just launched a website and wonder why there are no visitors!? The most frustrating thing is that Analytics was showing “data is being gathered”… Just made that fix will see how it works. Thanks for sharing!

  16. Just an addition to the fix; If your using Magento Compiler you’ll need to re-compile as this is one of the files thats cached and compiled.

  17. I think that my hoster will not be up for that 🙂 I also have a copy of the shop in a dev folder and changed also added the code there. This worked perfectly. The difference is that has never been switched on before.
    Somehow it keeps the wrong information in some sort of cache?

  18. @Edward
    I’m not entirely sure why but manually restarting the apache server fixed the problem in my case. Seemed a bit overkill though.

  19. Hi,

    thanks for this fix. However, I did the fix, but is does not alter the code on the webpages. If I look on the source it still shows up without the added line.
    Even after a cache flush.

    Any ideas?

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.