Take your e-commerce store further.

Using the right Magento 2 extension is more essential now than ever. With MagePal, you can rest assured that you are getting the best quality Magento extensions, each line of code are carefully crafted and rigorously tested. Spend less time debugging and more time doing what you do best with MagePal extensions!

DataLayer for Google Tag Manager

What is DataLayer?

The DataLayer for Google Tag Manager extension provides a robust JavaScript data layer API that connects your Magento 2 store with Google Tag Manager. It structures and exposes rich catalog, customer, page, cart, and transaction data into standard dataLayer objects.

It provides a clean, standardized way to access and transform your Magento data for any marketing tag or analytics tool (such as GA4, Meta Pixel, Pinterest, TikTok, Bing UET, and Google Ads) with zero core template modifications.

Want to learn more about your customers? Gain valuable insight on your customers shopping behavior, sales performance and more. Upgrade to our new Google Analytics 4 (GA4) to take full advantage of Google Analytics most valuable features.

Installation Guide

Step 1 - Review License

Review the license.txt provided with your purchase.

Step 2 - Install DataLayer for Google Tag Manager (version 2.0.0 or greater for Magento 2.4.0 and above)

composer require magepal/magento2-data-layer

Using Hyvä Magento 2 Theme?

composer require hyva-themes/magento2-magepal-data-layer

Learn more about installing and setting up Google Tag Manager

Manually
  • Download and install our core extension:
    • https://github.com/magepal/magento2-core
  • Download the extension archive.
  • Unzip the archive.
  • Create the target directory: {Magento 2 root}/app/code/MagePal/DataLayer
  • Copy the contents from the unzipped folder into this directory.

Step 3 - Enable Module (from {Magento root} folder)

 php -f bin/magento module:enable --clear-static-content MagePal_GoogleTagManager
 php -f bin/magento module:enable --clear-static-content MagePal_DataLayer
 php -f bin/magento setup:upgrade

Step 4 - Extension Review

Like our extensions? Would you be kind enough to leave us a Google review? It only takes a minute and we’d be eternally grateful! Just click the link to go to our MagePal Google Business page and leave us your feedback.

Configure DataLayer for Google Tag Manager

DataLayer for Google Tag Manager Configuration

Step 5 - How to Configure DataLayer in Magento Admin

Log into your Magento 2 Admin

  1. Goto Stores
  2. Configuration
  3. MagePal
  4. Google Tag Manager
  5. Enable DataLayer

Setup your Tags, Triggers and Variables in Google Tag Manager

Google Tag Manager Setting

Step 6 - Log into your Google Tag Manager account

Google Tag Manager

After logging into your Google Tag Manager account, you will need to configure Google Tag Manager to send the information to Google Analytics once the various event happen. To do this you will need to follow the following instruction below.

  1. Choose “Tags”
  2. Then click “New”
  3. Click “Choose a tag type to begin setup”
  4. Click on “Google Analytics - Universal Analytics” for “tag type”
  5. Enter setting below for Track Type, Category, Action, Non-Interaction
  6. Click “Choose a trigger to make this tag fire…”
  7. Then click on the “+” sign to add a new “Trigger Configuration”
  8. Click “Choose a trigger type to begin setup…”
  9. Choose “Custom Event”
  10. Enter the “Event Name”
  11. Then save configuration.

Third-party Integration Guide

DataLayerApi - Data Helper Reference

Url Builder Helper Functions
/**
 * @param string domain
 * @return this
 */
 setUrlDomain(domain)

/**
 * @param object params
 * params = {key:'pair'}
 * @return this
 */
 addUrlParams(params)

/**
 * Reset url parameters  
 * @return this
 */
 resetParams()

/**
 * Build url string
 * @return string
 */
 buildUrl()
 
 /**
  * Create hidden iframe tag and open url
  * @return this
  */
 addIframe(url)
 
 /**
  * Create hidden image tag and open url 
  * @return this
  */
 addImage(url)
Sample usages
require(['DataLayerApi'], function (dataLayerApi) {
    var helper = dataLayerApi();
    
    var queryParms1 = {
        KEY: 'xyz',
        OID: 123,
    };
    
    var queryParms2 = {
        page_type: 'productDetail',
        price: 1,
    };

    helper.setUrlDomain('//test.magepal/tags/c/');
    helper.addUrlParams(queryParms1);
    helper.addUrlParams(queryParms2);
    
    //generate url test.magepal/tags/c/?KEY=xyz&OID=123&page_type=productDetail&price=1
    var url = helper.buildUrl();
    
    //create an iframe and open url
    helper.addIframe(url);
    
    //creat hidden iframe and open url
    helper.addImage(url)
});
/**
 * Get Url query string parameter by name
 */
getParameterByName(name)

/**
 * Set Cookie
 */
setCookie(name, value, lifetime)

/**
 * Get cookie by name
 */
getCookie(name, deleteCookie)

/**
 * Delete cookie by name
 */
deleteCookie(name)

/**
 * Save cookie if url query string exist
 * Helper function for getParameterByName() and setCookie()
 * @param urlParameter
 * @param cookieName
 * @param expiration
 * @return {boolean}
 */
saveTrackingCodeIfKeyExist(urlParameter, cookieName, expiration)

/**
 * Retrieve cookie if exist
 * @param cookieName
 * @param deleteCookie bool
 */
getTrackingCodeIfKeyExist(cookieName, deleteCookie)
Sample usages
require(['DataLayerApi'], function (dataLayerApi) {
    var helper = dataLayerApi();
    
    expiration = 60 * 60 * 24 * 30;
    urlParameter = 'referenceId'
    //get query string value if exist
    var value = helper.getParameterByName(urlParameter);
    
    //save value if exist to a cookie
    if (value !== null && value !== '') {
        cookieName = 'referenceId';
        helper.setCookie(cookieName, value, expiration);
    }
});
DataLayerApi - General Helper Functions

/**
 * Get Currency Code
 * @param defaultCode
 * @return string
 */
getCurrencyCode(defaultCode)

/**
 * To csv
 * @param arr
 * @return string
 */
toCsv(arr)

/**
 * To csv
 * @param arr
 * @return string
 */
toTsv(arr)
       

DataLayerCustomerApi - Customer Data Helper Reference

General Helper Functions
/**
 * Get customer data
 * @param sKey
 * @param defaultValue
 * @return object | mix
 */
getCustomer(sKey, defaultValue)

/**
 * Get customer id
 * @param defaultValue
 * @return int
 */
getId(defaultValue)

/**
 * Get customer email address
 * @param defaultValue
 * @return string
 */
getEmail(defaultValue)

/**
 * Get get email sha1
 * @param defaultValue
 * @return string
 */
getEmailSha1(defaultValue)

/**
 * Get customer Website Id
 * @param defaultValue
 * @return int
 */
getWebsiteId(defaultValue)
       

DataLayerCategoryApi - Product Data Helper Reference

Includes all the base functionality of DataLayerApi
/**
 * Get data element by key
 * @param sKey
 * @param defaultValue
 * @return {*|*|string}
 */
getCategory(sKey, defaultValue)

/**
 * Get data element by key
 * @param sKey
 * @param defaultValue
 * @return {*|string|*}
 */
getCategoryItem(sKey, defaultValue)

/**
 * Get Production Impression collection
 * @return {Array|*}
 */
getProductImpressions()

/**
 * Get Product Impression SKUs
 * @param fieldName
 * @param options
 * @return {*|Array|string}
 */
getProductSkus(fieldName, options)

/**
 * Return product detail
 */
getCategoryDetail()

DataLayerProductApi - Product Data Helper Reference

Includes all the base functionality of DataLayerApi
/**
 * Get data element by key
 * @param sKey
 * @param defaultValue
 * @return {*}
 */
getProduct(sKey, defaultValue)

/**
 * Get data element by key
 * @param sKey
 * @param defaultValue
 * @return {*|string|*}
 */
getProductItem(sKey, defaultValue)

/**
 * Get Product collection
 * @param options
 * @return {Array|*}
 */
getProductCollection(options)

/**
 * Get Skus
 * @param fieldName
 * @param options
 * @return {*[]|*|Array|string}
 */
getProductSkus(fieldName, options)

/**
 * Return product detail
 * @return {}
 */
getProductDetail()

/**
 * Get Item added to cart
 * @param options
 * @return {Array|*}
 */
getAddedToCartItems(options)

/**
 * Get total for item added to cart
 * @return float
 */
getAddedToCartTotal()

/**
 * Get skus added to cart
 * @param fieldName
 * @param options
 * @return {*|Array|string}
 */
getAddedToCartItemSkus(fieldName, options)

/**
 * Get items removed from cart
 * @param options
 * @return array
 */
getRemovedFromCartItems(options)

/**
 * Get item removed from cart
 * @return float
 */
getRemovedFromCartTotal()

/**
 * Get item removed from cart qty
 * @return int
 */
getRemovedFromCartQty()

/**
 * Get skus of item removed from cart
 * @return array | string
 */
getRemovedFromCartItemSkus(fieldName, options)

DataLayerCheckoutApi - Checkout Data Helper Reference

Extend all the base functionality of DataLayerApi
/**
 * Get data element by key
 * @param sKey
 * @param defaultValue
 * @return {}
 */
getCart(sKey, defaultValue)

/**
 * Get data element by key
 * @param sKey
 * @param defaultValue
 * @return {}
 */
getCartItem(sKey, defaultValue)

/**
 * Get Items
 * @param options {appendIndex: bool, renameFieldTo: {fromKey:to, ...}}
 * @return {*}
 */
getItems(options)

/**
 * Get item count
 * @return {}
 */
getItemCount()
/**
 * Get quote items SKUs
 * @param fieldName
 * @param options {appendIndex: bool, renameFieldTo: {fromKey:to, ...}}
 * @return {Array|string}
 */
getSkus(fieldName, options)

DataLayerPurchaseApi - Purchase Data Helper Reference

Extend all the base functionality of DataLayerApi
/**
 * Get data element
 * @param sKey
 * @param defaultValue
 * @return {*|string|*}
 */
getOrder(sKey, defaultValue)

/**
 * Get items orders
 * @param format {appendIndex: bool, renameFieldTo: {fromKey:to, ...}}
 * @return {}
 */
getItems(options)

/**
 * Get purchase items SKUs
 * @param fieldName object
 * @param options {format: 'csv'|'tsv'}
 * @return array
 */
getSkus(fieldName, options)

/**
 * Get item count
 */
getItemCount()

/**
 * get Payment Method
 * @param name
 * @param defaultValue
 * @return {string}
 */
getPaymetMethod(name, defaultValue)

/**
 * get Shipping Method
 * @param name
 * @param defaultValue
 * @return {*|string|*}
 */
getShippingMethod(name, defaultValue)

Data Layer Customization | API

Add more information to the data layer to meet your client needs is as simple as extending our API.

Extending Data

define([
    'jquery',
    'underscore',
    'DataLayerApi'
], function ($, _, Component) {
    'use strict';

    return Component.extend({
        /**
         * Add new method 
         * Hello World
         */
        getHelloWorld() {
            return 'hello world';
        },
        /**
         * Extend existing functionality
         * Get Currency Code
         * @return string
         */
         getCurrencyCode: function (defaultCode) {
             var code = this._super(defaultCode);
             
             if (code == 'xyz') {
                 return 'USD';
             }
         }
        
    });
});

Debugging Google Tag Manager

Even the most advanced Google Tag Manager users often run into issues while setting up new tags. Frustrated by the process we often ask ourselves, why doesn’t my tag fire, what data is sending to Google Analytics, and why didn’t this trigger work?

One of the most overlooked, yet important steps while working with GTM is its preview and debugging mode. Google Tag Manager’s preview mode allows you to preview your container code as if the current container draft was deployed so that you can test your configuration before it is published.

Preview and Debugging Google Tag Manager

Enable preview mode

To enable preview mode, click Preview. Google Tag manager will display a banner across the top of the workspace overview page to indicate that preview mode is active.

Preview and Debugging Google Tag Manager

Once preview mode is enabled a debug pane will display at the bottom of your browser content, which display all the fired tags fired, which data is available on the data layer at that moment in time and the order the tags are firing.

Version History | Change Log

2.0.2

  • New Features:
    • Add support for PHP 8.5 and Magento 2.4.9
    • Add support for wishlist add and remove data layer events (add_to_wishlist, remove_from_wishlist)

2.0.1

  • New Features:
    • Add support for Magento 2.4.8 and PHP 8.4

2.0.0

  • New Features:
    • Add Content Security Policy (CSP) support
    • Discontinued support for Magento versions 2.0.x, 2.1.x, 2.2.x, and 2.3.x

1.7.11

  • New Features:
    • Add support for PHP 8.3

1.7.10

  • New Features:
    • Update Google Ads Enhanced Conversion data structure

1.7.9

  • New Features:
    • Update Google Ads Enhanced Conversion Data with SHA256 hashed customer details and phone formatting

1.7.8

  • Fixed bugs:
    • Fix TikTok tracking issues by adding TikTok item helper functions for cart, checkout, and purchase

1.7.7

  • Fixed bugs:
    • Fix PHP 7.3 compatibility in CouponAddedPlugin

1.7.6

  • New Features:
    • Add support for Magento 2.4.6 and PHP 8.2

1.7.5

  • New Features:
    • Implement add/remove coupon events
  • Fixed bugs:
    • Fix swatch selected option checking in swatch-renderer-mixin

1.7.4

  • New Features:
    • Add support for PHP 8.1
    • Invalidate customer section on customer login post

1.7.3

  • Fixed bugs:
    • Fix issue with subscription and retrieving customer data from session storage

1.7.2

  • New Features:
    • Add email sha1 data to Customer Log In, Customer Registration, and Newsletter Subscription

1.7.1

  • New Features:
    • Add support for Google Ads Enhanced Conversions
    • Add customer conversion reporting for Smart Shopping campaigns

1.7.0

  • New Features:
    • Add support for Google Analytics 4 & Google Enhanced Ecommerce working side by side

1.6.0

  • New Features:
    • Add support for Google Analytics 4
  • Fixed bugs:
    • Remove the url and image_url data layer fields to prevent GA4 issues

1.5.5

  • Fixed bugs:
    • Fixed issue in checkoutApi for Facebook tracking

1.5.4

  • Fix dependency-injection compilation errors

1.5.3

1.5.2

  • Fix the “Maximum call stack size exceeded” JavaScript error

1.5.1

  • Add support for Magento 2.4.0
  • Add support for PHP 7.4

1.5.0

  • Add Login, Newsletter, Registration, Log out events
  • Add events for when a swatch selected

1.4.1 (Unreleased)

  • Add page events
  • Add swatch click event
  • Add swatch option selected data values

  • Fix error in getTrackingCodeIfKeyExist() - add ‘return’
  • Fix error in getEmail() - add ‘return’
  • Fix issue with product.getRemovedFromCartQty()
  • Add product.getAddedToCartQty()

1.4.0

  • Add data layer API for all major pages

1.1.1

  • Fix “DataLayer extension module. data.js; line 273: formatObjectWithIndex is not a function”

1.1.0

  • First release

Related Extensions

Get more from your Magento2 store!

Enhanced Transactional Emails

Get more from your order confirmation emails by promoting other complementary products.

Enhanced Success Page

Add cross-sell, upsell, related products, social media links and other elements to your order confirmation.

HTML Minifier for Magento2

Minification is the process of removing all unnecessary characters and spacing from your source code without changing its functionality.

0

Total Downloads

11

years experience with Magento

30+

Magento / Adobe Commerce Extensions

Shop with confidence

With millions of downloads worldwide, install with confidence knowing that our extensions will just work.

Prepare for the future with Google Analytics 4

Is your Magento store ready for the future? Say hello to the new Google Analytics 4, which is built from the ground up with all-new features and advanced machine learning technology.

Learn More