• Services

    IT SERVICES

    solutions for almost every porblems

    Ecommerce Development

    Enterprise Solutions

    Web Development

    Mobile App Development

    Digital Marketing Services

    Quick Links

    To Our Popular Services
  • Hire Developers

    Hire Developers

    OUR ExEPRTISE, YOUR CONTROL

    Hire Mangeto Developers

    Hire Java Developers

    Hire Node Developers

    Hire Shopify Developers

    Hire Android Developers

    Hire Angular Developers

    Hire Shopware Developers

    Hire iOS App Developers

    Hire WordPress Developers

    Hire A full Stack Developer

    Choose a truly all-round developer who is expert in all the stack you require.

  • Case Studies
  • About
  • Blog
  • Contact Us
Implement GA4 Ecommerce Tracking on Magento 2 without Extension
Updated on 28/06/2024

Implement GA4 Ecommerce Tracking on Magento 2 without Extension

ecommerce Magento

GA4 is the new tracking tool introduced in 2020 which worked alongside the then primary Universal Analytics (UA). GA4 brought a new event-based tracking approach which is much simpler, streamlined and platform independent compared to UA. By late 2022 Google started pushing GA4 as default tracking method, and in July 2023, Google officially discontinued Universal Analytics.

Though event tracking in GA4 is backward compatible, meaning your existing UA events should work on GA4 as well, however it is always a good idea to update the data tracking as per the GA4 recommended guidelines.

Magento 2 is very slow in bringing GA4 support, it still does not have full official full support for GA4 tracking despite being the primary tracking method for most. Though they did add inbuilt GA4 tracking method from version 2.4.5, but you will still need to push the data to GA4 in order to track the e-commerce events, as it is not done automatically in Magento.

There are two ways of how you can implement ecommerce tracking in Magento 2, one using a 3rd party extension or via custom implementation. In this article we will explore the later option of how you can implement GA4 manually on Magento 2 without 3rd party extensions. If you even have the very basic knowledge of PHP, Magento and JSON you can follow this tutorial and implement tracking in no time.

Prerequisites

Before we dive into the setup, make sure you understand the basic requirements:

  1. A Google Tag Manager account and container.
  2. A Google Analytics 4 property.
  3. Access to your Magento 2 admin panel.
  4. Basic understanding of PHP, Magento 2 template and JavaScript.

 

If you are ready with the above items, let’s get started

Need help of a Magento Developer to implement the tracking?

Ecommerce Development

Adding GTM Tracking Tag in Magento 2

Once you create an account and a container you will find a tracking tag from the container dashboard in google tag manager.

Image of GTM container

In order to accurately track the data from your website, you will need to add a snippet of code inside the head and a snippet of code inside the body tag. There are few ways of doing it extension being the easiest, or we can add it from the admin > content > theme config settings.

But since we care about doing a manual implementation let’s go with the most efficient and robust option. Adding head tag to from the admin and body tag into the code.

Hire a dedicated developer for cross-platform API integration

Adding GTM Snippet into the head section

Copy the snippet for head from your GTM container

GTM snippit for Head

Adding the code in the head is pretty simple:

  1. Login to your Magento Admin
  2. Find the content tab from the side bar and navigate to content > design > configuration
  3. Edit the active theme and paste the code snippet for head section inside HTML Head > Script and Styles Sheet

Adding GTM no script snippet inside the body

Google recommends adding this <noscript> snippet immediately after the opening of the body tag which cannot be managed from the admin panel. Though, if you want to do it from the admin panel, many in the Magento community suggest adding it in the Miscellaneous HTML found under content > design > configuration > active themes > Footer

However, it is worth noting that the above method is not the most reliable, and we would recommend adding the snippet tag directly into the default layout file or a custom module file.

Step 1: Navigate to your ‘default.xml’ Layout File

Since we are going to create a dedicated module, we will be creating a default.xml file inside the module folder in the following path view/frontend/layout

Step 2 Insert a Reference Container for noscript tag in default layout

Open default.xml and add the GTM <noscript> tag just after the opening <body> tag

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="after.body.start">
            <block class="Magento\Framework\View\Element\Template" 
                   name="custom.view.item.datalayer" 
                   template="Azguards_CustomGTM::html/gtm.phtml"/>
        </referenceContainer>
    </body>
</page>

Step 3 Create the gtm.phtml File

Create a new file named gtm.phtml in view/frontend/templates/html

And add the <noscript> tag you find in GTM dashboard in that file.

GTM snippit for Body

Deploy the Static files and Clear the caches

First run the command to deploy the static files then run the commands to clear the caches

php bin/magento setup:static-content:deploy

php bin/magento cache:clean
php bin/magento cache:flush

Verify GTM Installation

Check Your Website:

  • Open your website and view the source code (Right-click > View Page Source).
  • Ensure that both the GTM <script> and <noscript> tags are present in the correct locations.


Awesome!! Now you are ready to connect your GA4 with Google Tag Manager

Need our assistance in setting up the tag on your Magento website?

Get In Touch

Creating a GA4 Configuration Tag in GTM

GA4 configuration tag enables the connection between your GTM container and in other words setting up this tag will enable GA4 tracking on your website.

1. Open your GTM container then navigate to Tags > New

2. Choose Google Tag

Creating new Google Tag

3. Enter your GA4 Measurement ID (found in your GA4 data stream settings)

Measurement ID found in Data stream settings in GA4

4. Create configuration parameter under configuration settings as shown in the below image

Google Tag Config

Save the tag and name it appropriately.

Hurray🎉🎉 You have successfully set up the GA4 tag on your Magento website. Now you should be able to view the traffic of your Magento 2 store in Google Analytics.

Now let’s continue with the real exciting part, setting up Google recommended events.

Hire a dedicated developer for cross-platform API integration

Setting Up Ecommerce Tracking

Google’s Recommended Ecommerce events

Google has provided a list of recommended events that might be added to an ecommerce site for comprehensive tracking via GA4. However, we will not dive into all of them in this article to keep the length of the manageable, rather we will only focus on four core events for all e-commerce businesses which are

  1. View Product
  2. Add To Cart
  3. Checkout
  4. Purchase

 

If you want to find out learn more about the recommended event, you can refer to the following documentation by google

  • https://support.google.com/analytics/answer/9267735?hl=en
  • https://developers.google.com/analytics/devguides/collection/ga4/ecommerce?client_type=gtm

Creating Essential Variables

There are multiple steps that you need to take in GTM in order to pass the data from dataLayers to GA4. But setting up variables for commonly used values can make our life much easier. This is how you create the variables

Variable For Measurement ID

Creating a variable for measurement ID is not essential but it is very convenient, efficient and will be required in each of the events.

1. Go to GTM Dashboard select Variables tab from the sidebar
2. Create new user defined variable
3. Select Variable Configuration > Utilities > Constant
4. Add the measurement ID found in your GA4 under the data stream
5. Add name of the Variable, and Save
Setting up variable for Ga4 measurement ID

Creating dataLayer Variables

The good thing about GA4 is that it has a very flat structure, so you will need to define fewer variables and it is way easier to manage,

We will need to create a variable for currency, value and items data. It is very easy to do in the google tag manager

So, like we did in the last time, 

Go to GTM Dashboard > Variables from the sidebar

Create a new user defined variable

Then click variable Configuration > Data Layer Variable

Configure Variable as follows

  1. Under the “Data Layer Variable Name” should be exactly how it is defined in the data layer. In our case for currency, it would be
  2. Data Layer Variable Name – “ecommerce.currency”
  3. Variable Name “CURRENCY” (you can choose any name that you want, but make sure it is unique and recognizable)
  4. Save the setting

We will do same for the other other dataLayer variables that will be used in setting up the ecommerce events later in the articles:

Data layer variable config for “Value”

Data layer variable for “items”

GTM Variables Setup items array

Creating Custom Triggers for Events

We need to create custom triggers which will watch for a dataLayer event to happen and once it happens it fires the GTM event.

We need to create a custom trigger for each of the events, but it is pretty simple.

Navigate to triggers from the sidebar of your GTM container

Now click on New > Trigger Configuration

Then from the sidebar navigate to Other > Custom Trigger

In Custom Trigger add event name exactly as defined in the dataLayer.

Not at last give a meaningful name to the trigger and save.

For this blog we will need to create triggers for 4 events, i.e.

  1. view_item,
  2. add_to_cart,
  3. begin_checkout,
  4. purchase

You can refer to the slider below

GA4 - Custom Trigger - Purchase
GA4 - Custom Trigger - Begin Checkout
GA4 - Custom Trigger - Add To Cart
GA4 - Custom Trigger - View Item
GA4 - Custom Trigger - Purchase
GA4 - Custom Trigger - Begin Checkout

Tracking Product View (view_item)

Add Data Layer in for view_item

Create catalog_product_view.xml, inside view/frontend/layout and paste the following code

<?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="head.additional">
            <block class="Magento\Catalog\Block\Product\View" 
            name="custom.view.item.datalayer" 
            template="Azguards_CustomGTM::datalayer/view_item.phtml"/>
        </referenceContainer>
    </body>
</page>

Create the Template File

In your custom module or theme, create view_item.phtml if you are building along with us place it inside view/frontend/templates/datalayer

<?php
/** @var \Magento\Catalog\Model\Product $product */
$product = $block->getProduct();
?>
<script type="text/javascript">
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': 'view_item',
        'ecommerce': {
            'currency': '<?php echo $block->escapeHtml($product->getStore()->getCurrentCurrencyCode()); ?>',
            'value': '<?php echo $block->escapeHtml($product->getPrice()); ?>',  // Assuming price represents total value
            'items': [{
                'item_name': '<?php echo $block->escapeHtml($product->getName()); ?>',
                'item_id': '<?php echo $block->escapeHtml($product->getSku()); ?>',
            
            }]
        }
    });
</script>

Create an event in GTM to capture view_item even

Goto from GTM dashboard, sidebar > Tags > New

Tag Configuration:  Google Analytics > Google Analytics: GA4 Event

Add the GA4 Measurement ID

Event Name: view_item (it has to be exactly as defined in dataLayer)

Add Event Parameters, set variables created in previous step as a value for each parameter

  • currency: {{CURRENCY}}
  • value: {{PRICE}}
  • Items: {{ITEMS}}

Set trigger to custom event for View Item

 

Event Setup View Items

Tracking Add To Cart (add_to_cart)

Caution: Make sure you have basic knowledge of Magento in order to proceed further, these steps might break some core functionality if not done correctly.

Modify add-to-cart.js

Modify the JavaScript handling the add-to-cart functionality to include a data layer push. Magento 2 uses AJAX to handle add-to-cart actions. You can extend or override the default Magento JavaScript to include the data layer push.

Create a RequireJS Mixins File

Create a custom RequireJS mixin to extend the functionality of the default add-to-cart process.

Create requirejs-config.js inside view/frontend

var config = {
    config: {
        mixins: {
            'Magento_Catalog/js/catalog-add-to-cart': {
                'Azguards_CustomGTM/js/catalog-add-to-cart-mixin': true
            }
        }
    }
};

Create the Mixin JavaScript

Extend the catalog-add-to-cart JavaScript file to push the add_to_cart event to the data layer.

Create catalog-add-to-cart-mixin.js inside view\frontend\web\js

define([
    'jquery'
], function ($) {
    'use strict';

    return function (widget) {
        $.widget('mage.catalogAddToCart', widget, {
            submitForm: function (form) {
                var self = this;
                $.ajax({
                    url: form.attr('action'),
                    data: form.serialize(),
                    type: 'POST',
                    dataType: 'json',
                    success: function (response) {
                        var productData = {
                            item_name: form.find('[name=product]').data('name'),
                            item_id: form.find('[name=product]').val(),
                            price: form.find('[name=price]').val(),
                            quantity: form.find('[name=qty]').val() || 1
                        };
                        window.dataLayer = window.dataLayer || [];
                        window.dataLayer.push({
                            'event': 'add_to_cart',
                            'ecommerce': {
                                'currency': 'USD',
                                'value': productData.price * productData.quantity,
                                'items': [productData]
                            }
                        });

                        if (response.backUrl) {
                            self._redirect(response.backUrl);
                            return;
                        }
                        self._showMessage(response);
                    },
                    error: function (response) {
                        console.log('AJAX request failed', response); 
                    }
                });
                return false;
            },

            /**
             * Displays a message based on the response
             *
             * @param {Object} response
             */
            _showMessage: function (response) {
                if (response && response.messages) {
                    $(this.options.messagesSelector).html(response.messages);
                }
            }
        });

        return $.mage.catalogAddToCart;
    };
});

Deploy the Changes

bin/magento setup:upgrade
bin/magento setup:static-content:deploy
bin/magento cache:clean

Create an event in GTM to capture add_to_cart event

Setting up all the events will be pretty similar to what we did in the last view_product event. Let’s quickly look into it.

We will not need to create any new variable for this event, as it only requires the variables created in the last step i.e. currency, value, and items.

Checkout the following image and configure it similarly:

Add Event Parameters:

  • currency: {{CURRENCY}}
  • value: {{PRICE}}
  • Items: {{ITEMS}}

Set the custom trigger we created earlier for Add to Cart

Tracking Checkout (begin_checkout)

Add Data Layer in Magento 2 Theme

Create a checkout_index_index.xml file inside view/frontend/layout

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="head.additional">
            <block class="Magento\Framework\View\Element\Template" 
                name="custom.begin.checkout.datalayer" 
                template="Azguards_CustomGTM::datalayer/begin_checkout.phtml"/>
        </referenceContainer>
    </body>
</page>

Create Template File

In your custom module create “begin_checkout.phtml” inside view/frontend/templates/datalayer and add the following snippet

<?php
/** @var \Magento\Checkout\Model\Cart $cart */
$cart = $this->helper('Magento\Checkout\Helper\Cart');
$items = $cart->getQuote()->getAllVisibleItems();
$products = [];
foreach ($items as $item) {
    $product = $item->getProduct();
    $products[] = [
        'item_name' => $product->getName(),
        'item_id' => $product->getSku(),
        'price' => $item->getPrice(),
        'quantity' => $item->getQty()
    ];
}
?>
<script type="text/javascript">
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': 'begin_checkout',
        'ecommerce': {
            'currency': '<?php echo $block->getCurrencyCode(); ?>',
            'value': '<?php echo $cart->getQuote()->getGrandTotal(); ?>',
            'items': <?php echo json_encode($products); ?>
        }
    });
</script>

Creating a Tag in Google Tag Manager

By this time, I think you should be pretty familiar with the drill. Still, checkout the following image for tag configuration

Add Event Parameters:

  • currency: {{CURRENCY}}
  • value: {{PRICE}}
  • Items: {{ITEMS}}

Set the custom trigger for Begin Checkout

Tracking Purchase (purchase)

Fetching Purchase Data

Create a file Gtm.php to fetch purchase data, in your module inside Block/Onepage

<?php
namespace Azguards\CustomGTM\Block\Onepage;

use Magento\Framework\View\Element\Template;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Sales\Model\Order;

class Gtm extends Template
{
    protected $checkoutSession;
    protected $order;

    public function __construct(
        Template\Context $context,
        CheckoutSession $checkoutSession,
        Order $order,
        array $data = []
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->order = $order;
        parent::__construct($context, $data);
    }

    public function getOrder()
    {
        $orderId = $this->checkoutSession->getLastOrderId();
        return $this->order->load($orderId);
    }
}

Add Data Layer in Success.phtml file

Success page is slightly unique don’t need to create a reference block unlike the previous flows. You can directly add the snippet in the success.phtml which needs to be inside view/frontend/templates/checkout.

<?php
/** @var \Azguards\CustomGTM\Block\Onepage\Gtm $block */
$order = $block->getOrder();
$items = $order->getAllVisibleItems();
$products = [];
foreach ($items as $item) {
    $products[] = [
        'item_name' => $item->getName(),
        'item_id' => $item->getSku(),
        'price' => $item->getPrice(),
        'quantity' => $item->getQtyOrdered()
    ];
}
?>
<script type="text/javascript">
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
        'event': 'purchase',
        'ecommerce': {
            'transaction_id': '<?php echo $block->escapeHtml($order->getIncrementId()); ?>',
            'value': '<?php echo $block->escapeHtml($order->getGrandTotal()); ?>',
            'currency': '<?php echo $block->escapeHtml($order->getOrderCurrencyCode()); ?>',
            'items': <?php echo json_encode($products); ?>
        }
    });
</script>

Create a for purchase event in Google Tag Manager

As you might have guessed, setting up purchase event is pretty similar to previous events, all thanks to the flat structure GA4 specifications. Just need to pass one additional value of transaction id. 

Configure the tags as per the following image:

Add Event Parameters:

  • transaction_id:  {{TRANSACTION ID}}
  • currency: {{CURRENCY}}
  • value: {{PRICE}}
  • Items: {{ITEMS}}

Set the trigger to 

Finally, Run the following commands and make sure the code is deployed correctly

bin/magento setup:upgrade
bin/magento setup:static-content:deploy
bin/magento cache:clean

Your GA4 is ready to track ecommerce events!

Were you able to follow along the tutorial and setup the most critical ecommerce event on your Magento 2 store.

This data will give you valuable insights about your sales funnel and how you can optimize the conversion.

However, there are many other ecommerce events that you can track on your site which can give you even better insights about your customer behavior like tracking add_to_wishlist, or tracking the search queries to understand what product or category are popular among your customers, and what your customers actually want.

Additionally, you can also set up events for cancellations and refunds, or track performance of promotions. You can find all the tag from google guide link below

Would you like to integrate Whatsapp or APIs into your website or mobile app?

Feel Free To Contact Our Experts

Would you like to share this article?

Share
If you have an issue send your query

Post Content

Prerequisites
Adding GTM Tracking Tag in Magento 2
Creating a GA4 Configuration Tag in GTM
Setting Up Ecommerce Tracking
Finally, Run the following commands and make sure the code is deployed correctly
Your GA4 is ready to track ecommerce events!

All Categories

Artificial Intelligence
ChatGPT
Communication
ecommerce
Magento
News and Updates
Technical
UX and Navigation
WhatsApp API
CTA Image for further description

Latest Post

  • Magento 2 Rich Text Schema Setup in JSON-LD: Step-by-Step Guide
  • Fixing Magento 2 Product Schema Markup | Missing “image” field FIX
  • How to Dispatch Custom Events in Magento 2
  • Adding Filters in Magento Admin Grid | Column and Non-Column Component
  • How to add custom styles (Colors and Fonts) to Magento Admin Grid
Free consultation

Related Post

  • Magento 2 Rich Text Schema Setup in JSON-LD: Step-by-Step Guide
  • Fixing Magento 2 Product Schema Markup | Missing “image” field FIX
  • How to Dispatch Custom Events in Magento 2
  • Adding Filters in Magento Admin Grid | Column and Non-Column Component
  • How to add custom styles (Colors and Fonts) to Magento Admin Grid

310 Kuber Avenue, Near Gurudwara Cross Road, Jamnagar – 361008

Plot No 36, Galaxy Park – II, Morkanda Road,
Jamnagar – 361001

Quick Links

  • About
  • Career
  • Case Studies
  • Blog
  • Contact Us
  • Privacy Policy
Icon-facebook Linkedin Google Clutch Logo White

Our Expertise

  • eCommerce Development
  • Web Development Service
  • Enterprise Solutions
  • Mobile App Development
  • Digital Marketing Services

Hire Dedicated Developers

  • Hire Full Stack Developers
  • Hire Certified Magento Developers
  • Hire Top Java Developers
  • Hire Node.JS Developers
  • Hire Angular Developers
  • Hire Android Developers
  • Hire iOS Developers
  • Hire Shopify Developers
  • Hire WordPress Developer
  • Hire Shopware Developers

Copyright @Azguards Technolabs 2025 all Rights Reserved.