How to add ecommerce tracking with gtag in magento order success

By | April 10, 2022
Spread the love

Every merchant wants to track their sales in google analytics. Currently google have changed google analytics (GA) to google tag manager(GTag). If you use gtm.js as your Google Analytics tag and you have Ecommerce reporting enabled, you can measure ecommerce transactions.

        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],


To measure a transaction, send a purchase event with the items in the transaction. For example:

<?php if($order && $order->getId()):?>
<script type="text/javascript">
var i = 0;
var items = [];
<?php foreach($order->getAllVisibleItems() as $item):?>
        $categoryName = '';
        $product      = ObjectManager::getInstance()->create("\Magento\Catalog\Model\Product")->load($item->getProductId());
        if($product && $product->getId() && $product->getCategoryIds()){
            $categoryIds  = $product->getCategoryIds();
            if (isset($categoryIds[0])){
                $category     = ObjectManager::getInstance()->create("\Magento\Catalog\Model\Category")->setStoreId(1)->load($categoryIds[0]);
                $categoryName = $category->getName();
    items[i] = {
         item_id: '<?php echo $item->getSku()?>',
         item_name: "<?php echo $item->getProduct()->getName()?>",
         affiliation: "xxxxxxx",
         currency: "USD",
         discount: <?php echo number_format($order->getDiscountAmount(),2)?>, 
         index: i,
         item_brand: "<?php echo $item->getProduct()->getBrandName()?>",
         item_category: "<?php echo $categoryName;?>",
         item_variant: "main",
         price: <?php echo number_format($item->getPrice(),2); ?>,
         quantity: <?php echo intval($item->getQtyOrdered())?>,
<?php endforeach;?>

dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
  event: "purchase",
  ecommerce: {
      transaction_id: '<?php echo $order->getIncrementId();?>', 
      affiliation: "xxxxxx",
      value: <?php echo number_format($order->getGrandTotal(),2); ?>,
      tax: <?php echo number_format($order->getTaxAmount(),2)?>,
      shipping: <?php echo number_format($order->getShippingAmount(),2); ?>,
      discount: <?php echo number_format($order->getDiscountAmount(),2)?>, 
      currency: "USD",
      coupon: "<?php echo $order->getCouponCode();?>",
      items: items
<?php endif;?>


See google guide here