Magento


12
Nov 09

How to install Google Affiliate pixel tracking code in Magento

Took me a day of scouring the web to figure out how to get this to work. After adding this code do a test order and view source and confirm it worked.

#copy and paste to the bottom of
#app/design/frontend/default/theme_name/template/checkout/success.phtml
$companyID = "K123456"; #provided by Google
$category = urlencode("Your product category");
$lastorderid = Mage::getSingleton('checkout/session')->getLastOrderId();
$_order = Mage::getModel('sales/order')->load($lastorderid);
$orderID = $this->getOrderId(); #get the order ID
$aProduct = array();
$totalAmt = 0;
$prdsku = "";
$prdnm = "";
$prdqn = "";
$prdpr = "";
$prcatid = "";

###########store order data in array of objects###########
foreach ($_order->getAllItems() as $item) {
	$oProduct = new stdClass();
	$oProduct->sku = $item->getSku(); #sku
	$oProduct->price = $item->getPrice(); #price
	$totalAmt = $totalAmt + ($oProduct->price * $item->getQtyOrdered()); #total amt (excl.tax/shipping)
	$oProduct->qty = $item->getQtyOrdered(); #quantity
	$oProduct->name = $item->getName(); #product name
	$oProduct->category = $category;
	array_push($aProduct, $oProduct);
	$oProduct = NULL; #nuke it
}
###########build query string variables###########
for ($i=0; $i < count($aProduct); $i++) {
	if ($i == count($aProduct)-1) {
		$prdsku .= urlencode($aProduct[$i]->sku);
		$prdnm .= urlencode($aProduct[$i]->name);
		$prdqn .= urlencode($aProduct[$i]->qty);
		$prdpr .= urlencode($aProduct[$i]->price);
		$prcatid .= urlencode($aProduct[$i]->category);
	} else {
		$prdsku .= urlencode($aProduct[$i]->sku) . "^";
		$prdnm .= urlencode($aProduct[$i]->name) . "^";
		$prdqn .= urlencode($aProduct[$i]->qty) . "^";
		$prdpr .= urlencode($aProduct[$i]->price) . "^";
		$prcatid .= urlencode($aProduct[$i]->category) ."^";
	}
}
?>