Skip to content

Commit

Permalink
Added order tracking for Google Analytics 4 (#3092)
Browse files Browse the repository at this point in the history
  • Loading branch information
fballiano committed Apr 11, 2023
1 parent 0445e04 commit dc45856
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
44 changes: 43 additions & 1 deletion app/code/core/Mage/GoogleAnalytics/Block/Ga.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,9 @@ protected function _getOrdersTrackingCode()
{
/** @var Mage_GoogleAnalytics_Helper_Data $helper */
$helper = $this->helper('googleanalytics');
if ($helper->isUseUniversalAnalytics()) {
if ($helper->isUseAnalytics4()) {
return $this->_getOrdersTrackingCodeAnalytics4();
} elseif ($helper->isUseUniversalAnalytics()) {
return $this->_getOrdersTrackingCodeUniversal();
}

Expand Down Expand Up @@ -190,6 +192,46 @@ protected function _getOrdersTrackingCodeUniversal()
return implode("\n", $result);
}

/**
* @return string
* @throws Mage_Core_Model_Store_Exception
*/
protected function _getOrdersTrackingCodeAnalytics4()
{
$orderIds = $this->getOrderIds();
if (empty($orderIds) || !is_array($orderIds)) {
return '';
}
$collection = Mage::getResourceModel('sales/order_collection')
->addFieldToFilter('entity_id', ['in' => $orderIds]);
$result = [];
/** @var Mage_Sales_Model_Order $order */
foreach ($collection as $order) {
$orderData = [
'currency' => $order->getBaseCurrencyCode(),
'transaction_id' => $order->getIncrementId(),
'value' => number_format($order->getBaseGrandTotal(), 2),
'coupon' => strtoupper($order->getCouponCode()),
'shipping' => number_format($order->getBaseShippingAmount(), 2),
'tax' => number_format($order->getBaseTaxAmount(), 2),
'items' => []
];

/** @var Mage_Sales_Model_Order_Item $item */
foreach ($order->getAllVisibleItems() as $item) {
$orderData['items'][] = [
'item_id' => $item->getSku(),
'item_name' => $item->getName(),
'quantity' => $item->getQtyOrdered(),
'price' => $item->getBasePrice(),
'discount' => $item->getBaseDiscountAmount()
];
}
$result[] = "gtag('event', 'purchase', " . json_encode($orderData, JSON_THROW_ON_ERROR) . ");";
}
return implode("\n", $result);
}

/**
* Render information about specified orders and their items
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ $_accountId = $_helper->getAccountId();
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<?= $_accountId ?>');
<?php echo $this->_getOrdersTrackingCodeAnalytics4() ?>
</script>
<!-- END GOOGLE ANALYTICS 4 CODE -->
<?php elseif ($_helper->isUseUniversalAnalytics()): ?>
Expand Down

0 comments on commit dc45856

Please sign in to comment.