Add Google Analytics tracking code on order success page in Magento

Add below code in template/checkout/success.phtml and do changes according to your requirement.

<?php
    $order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
?>
<script type="text/javascript">
    var _gaq = _gaq || [];
    //_gaq.push(['_setAccount', 'UA-50302108-1']);
    _gaq.push(['_trackPageview']);
    _gaq.push(['_addTrans',
        '<?php echo $this->getOrderId()?>',           // transaction ID - required
        '<?php echo Mage::app()->getWebsite()->getName()?>',  // affiliation or store name
        '<?php echo Mage::helper('core')->currency($order->getData('grand_total'), false, false);?>', // total - required
        '<?php echo Mage::helper('core')->currency($order->getData('tax_amount'), false, false);?>', // tax
        '<?php echo Mage::helper('core')->currency($order->getData('shipping_amount'), false, false);?>', // shipping
        '<?php echo $order->getShippingAddress()->getData('city');?>', // city
        '<?php echo $order->getShippingAddress()->getData('region');?>',     // state or province
        '<?php echo Mage::getModel('directory/country')->load($order->getShippingAddress()->getData('country_id'))->getIso3Code();?>' // country
    ]);

    <?php foreach($order->getAllVisibleItems() as $item): ?>
        <?php
            $cat_name = '';
            $ids = Mage::getModel('catalog/product')->load($item->getProductId())->getCategoryIds();
            if(count($ids) > 0)
            {
                $category = Mage::getModel('catalog/category')->load($ids[0]);
                $cat_name = $category->getName();
            }
        ?>
        _gaq.push(['_addItem',
            '<?php echo $this->getOrderId()?>', // transaction ID - required
            '<?php echo $item->getData('sku')?>', // SKU/code - required
            '<?php echo $item->getData('name')?>', // product name
            '<?php echo $cat_name;?>',   // category or variation
            '<?php echo Mage::helper('core')->currency($item->getData('price'), false, false);?>', // unit price - required
            '<?php echo intval($item->getData('qty_ordered'));?>'               // quantity - required
        ]);
    <?php endforeach; ?>

    _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

</script>


No comments:

Post a Comment