Magento – Magento2 Google analytics Conversion data on success page

conversiongoogle analyticsmagento2

I have a magento2.2.5 based website and even though I have Google analytics and adwards enabled I dont see conversion data.

So I spoke with google and was given the below code. However I do not know how to look through purchased items on the order success page and looking for suggestions??

 //getting order data
   $order = Mage::getModel('sales/order')->load($this->getOrderId());
   $grandtotalis = $oOrder->getGrandTotal();
   $grandtotalis = number_format($grandtotalis, 2, '.', '');
   $shipping = $oOrder->getShippingAmount();
   $tax = $oOrder->getTaxAmount();
   $store = Mage::app()->getStore();
   $thestorename = $store->getName();

<!-- Global site tag (gtag.js) - Google Ads: 789798816 -->

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'abcdefg');

 <!-- Event snippet for Sales Conversion New conversion page -->
 <script>
    gtag('event', 'conversion', {
         'send_to': 'ffff',
         'value': <?php echo "$grandtotalis"; ?>,
         'currency': 'USD',
         'transaction_id': '<?php echo $block->getOrderId();?>'
    });
 </script>
 <script type="text/javascript">
    ga('require', 'ecommerce');
    ga('ecommerce:addTransaction', {
       'id': '<?php $block->getOrderId(); ?>',   //Transaction ID. Required.
        'affiliation': '<?php echo "$thestorename":?>',   // Affiliation or store name.
        'revenue': '<?php echo "$grandtotalis";?>',               // Grand Total.
        'shipping': '<?php echo "$shipping";?>',                  // Shipping.
        'tax': '<?php echo "$tax";?>'                     // Tax.
   });

    ga('ecommerce:addItem', {
       'id': '<?php $block->getOrderId(); ?>',       // Transaction ID. Required.
       'name': 'Fluffy Pink Bunnies',    // Product name. Required.
       'sku': 'DD23444',                 // SKU/code.
       'category': 'Party Toys',         // Category or variation.
       'price': '11.99',                 // Unit price.
       'quantity': '1'                   // Quantity.
    });

   ga('ecommerce:send');
</script>

Best Answer

On the success page you have the LastOrderId available and with this order id you can get the items which are related to the placed order.

To do so you have to create a custom block but I would recommend to maybe use an existing extension for this feature.

For example:

Mageplaza_GoogleAnalytics - https://github.com/mageplaza/magento-2-google-analytics

In this module they have also created a custom block in which the LastOrderId is used:

https://github.com/mageplaza/magento-2-google-analytics/blob/master/Block/GoogleAnalytics.php#L42

Related Topic