1

Developer view, please

app/code/YourCompany/YourModule/etc/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<!-- <preference for="Magento\Catalog\Block\Product\View" type="Amf\GoogleAnalytics\Block\Catalog\Product\View" /> -->
<preference for="Magento\GoogleAnalytics\Block\Ga" type="YourCompany\YourModule\Block\Ga" />

Please let me know the best way

  1. copy files from vendor\magento\module-google-analytics\Block\Ga.php then modify the method.

  2. vendor\magento\module-google-analytics\Block\Ga.php - copy only required the method then do the modification.(code - https://textuploader.com/1a8x4)

Following point 1 error appears

Fatal error: Uncaught TypeError: Argument 4 passed to Magento\GoogleAnalytics\Block\Ga::__construct() must be of the type array, null given, called in app\code\YourCompany\YourModule\Block\Ga.php on line 57 and defined in vendor\magento\module-google-analytics\Block\Ga.php on line 45

Following point 2 block override done - just override method getOrdersTrackingCode() and getOrdersTrackingData

The solution for the issue mentioned here

0

You can override using following way.

Create your custom module and add following code in your app/Code/YourCompany/YourModule/etc/frontend/di.xml for block override.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">   
    <preference for="Magento\GoogleAnalytics\Block\Ga" type="YourCompany\YourModule\Block\Ga" />
</config>

And add your block file as per following.

So add following code in your app/Code/YourCompany/YourModule/Block/Ga.php

<?php

/**
 * Google Analytics Encoding Issue
 * 
 */
namespace YourCompany\YourModule\Block;

use Magento\Framework\App\ObjectManager;


class Ga extends \Magento\GoogleAnalytics\Block\Ga
{
    public function getOrdersTrackingCode()
    {
        $orderIds = $this->getOrderIds();
        if (empty($orderIds) || !is_array($orderIds)) {
            return;
        }

        $collection = $this->_salesOrderCollection->create();
        $collection->addFieldToFilter('entity_id', ['in' => $orderIds]);
        $result = [];

        $result[] = "ga('require', 'ec', 'ec.js');";

        foreach ($collection as $order) {
            $result[] = "ga('set', 'currencyCode', '" . $order->getOrderCurrencyCode() . "');";
            foreach ($order->getAllVisibleItems() as $item) {
                $result[] = sprintf(
                    "ga('ec:addProduct', {
                        'id': '%s',
                        'name': '%s',
                        'price': '%s',
                        'quantity': %s
                    });",
                    $this->escapeJsQuote($item->getSku()),
                    $this->escapeJsQuote($item->getName()),
                    $item->getPrice(),
                    $item->getQtyOrdered()
                );
            }

            $result[] = sprintf(
                "ga('ec:setAction', 'purchase', {
                    'id': '%s',
                    'affiliation': '%s',
                    'revenue': '%s',
                    'tax': '%s',
                    'shipping': '%s'
                });",
                $order->getIncrementId(),
                $this->escapeJsQuote($this->_storeManager->getStore()->getFrontendName()),
                $order->getGrandTotal(),
                $order->getTaxAmount(),
                $order->getShippingAmount()
            );

            $result[] = "ga('send', 'pageview');";
        }
        return implode("\n", $result);
    }

    public function getOrdersTrackingData()
    {
        $result = [];
        $orderIds = $this->getOrderIds();
        if (empty($orderIds) || !is_array($orderIds)) {
            return $result;
        }

        $collection = $this->_salesOrderCollection->create();
        $collection->addFieldToFilter('entity_id', ['in' => $orderIds]);

        foreach ($collection as $order) {
            foreach ($order->getAllVisibleItems() as $item) {
                $result['products'][] = [
                    'id' => $this->escapeJsQuote($item->getSku()),
                    'name' =>  $this->escapeJsQuote($item->getName()),
                    'price' => $item->getPrice(),
                    'quantity' => $item->getQtyOrdered(),
                ];
            }
            $result['orders'][] = [
                'id' =>  $order->getIncrementId(),
                'affiliation' => $this->escapeJsQuote($this->_storeManager->getStore()->getFrontendName()),
                'revenue' => $order->getGrandTotal(),
                'tax' => $order->getTaxAmount(),
                'shipping' => $order->getShippingAmount(),
            ];
            $result['currency'] = $order->getOrderCurrencyCode();
        }

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/GoogleAnalytics.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $logger->info(print_r($result,true));

        return $result;
    }

}

Please check and let me know if any issue.

  • please let me know which one best technique to implement? – Danes Feb 11 at 8:08
  • Please add both files fist one is for override your block file using di.xml and then add your override code in your block/Ga.php file – Aasim Goriya Feb 11 at 8:11
  • did you get that ? – Aasim Goriya Feb 11 at 8:22
  • Yes add this Ga.php file in your module – Aasim Goriya Feb 11 at 8:25
  • @Danes Second one is best technique to implement – Aasim Goriya Feb 11 at 8:30

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.