Danny Cui Danny Cui - 5 months ago 40
PHP Question

Magento Google Analytics Product Category not set

I am trying to track product category from magento to GA, (under Conversions>Ecommerce>overview), but with magento default core GA.php file dosent including this part:
/app/code/core/Mage/GoogleAnalytics/Block/Ga.php

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()
);
}


*see, they commend out category field and put null right there.

I am looking for a solution that do not modify the magento in the /core, but solve the problem in /local.

BTW, I am using magento 1.7

hopefully someone could help me out, many thx :D

Answer

I don't know much about Magento but I believe all you have to do is copy that whole file from core over to your /local folder and change it to include the category. Magento will always look for a file in /local before going to core, but the path have to match. So the file should live in:

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

Another problem you'll have is that Magento products can have several categories. so you probably want to grab just the first one and pass to GA.

So here's what the file should look like:

$_category = null;

$categoryIds = $_product->getCategoryIds();
if(count($categoryIds)) {
    $firstCategoryId = $categoryIds[0];
    $_category = Mage::getModel('catalog/category')->load($firstCategoryId);
}

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()),
        $_category,
        $item->getBasePrice(), $item->getQtyOrdered()
    );
}

Based in