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?

DataLayer is a JavaScript API that allows you to quickly and easily integrate any third-party Javascript with your Magento Store using Google Tag Magento. It provides an easy way to access and transform your Google Tag Manager data to match any specification with zero source code edits. Whether you want to integrate Bing, Facebook, SnapChat, Pinterest, or any other services.

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.txt

Step 2

Install Google Tag Manager (version 2.7.0 or greater)

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

Install DataLayer for Google Tag Manager

  • Download the extension
  • Unzip the file
  • Create a folder {Magento 2 root}/app/code/MagePal/DataLayer
  • Copy the content from the unzip folder

Step 4

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 5 - 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

Google Tag Manager

Step 3 - How to Configure Google Tag Manager

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

Step 4 - 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

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
  • Fixed bugs:
    • none

1.6.0

=============

  • New Features:
    • Add support for Google Analytics 4
  • Fixed bugs:
    • Remove datalayer element for url, image_url to prevent issue with GA4

1.5.5

=============

  • New Features:
    • none
  • Fixed bugs:
    • Fixed issue in checkoutApi for Facebook tracking

1.5.4

=============

  • New Features:
    • none
  • Fixed bugs:
    • Fix di compile issue introduce in 1.5.3

1.5.3

=============

1.5.2

=============

  • New Features:
    • Fix rear ‘Maximum call stack size exceeded’ Javascript error
  • Fixed bugs:
    • none

1.5.1


  • New Features:
    • Add support for 2.4.0
    • Add support for PHP 7.4
  • Fixed bugs:
    • none

1.5.0


  • New Features:
    • Add new page events (homePage, productPage, allPage, etc)
    • Add page handler events (catalogCategoryViewPage, catalogProductViewPage, etc)
    • Add events for Wish List (wishlistProductAdded, wishlistProductRemoved, productImpression)
    • Add Compare Products events (compareProductAdded, compareProductRemoved, productImpression)
    • Add Newsletter events (newsletterSubscriberAdded, newsletterUnsubscribed)
    • Add customers logged in events
    • Add customer registration event
    • Add helper method to get pre-formatted social media items
    • Add swatch selection events (productDetailSwatchClicked)
  • Fixed bugs:
    • minor code cleanup

1.4.1


  • New Features:
    • Add composer support for PHP 7.3.x
  • Fixed bugs:
    • Fix error in getTrackingCodeIfKeyExist() - add ‘return’

1.4.0


  • New Features:
    • Add API for each page layer and other enhancement
  • Fixed bugs:
    • 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!

Catalog Hover Image for Magento

Quickly previewing alternative product images on your category list page.

Enhanced Transactional Emails

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

Order Shipment Tracking

Providing your customer with a beautiful and functional order package tracking without leaving your site.

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