How to Integrate Google Analytics (GA) with Magento 2 Cookie Consent Extension

This guide will show you three options to easily set up Google Analytics with Magento 2 Cookie Consent extension and enable it for a particular cookie category.

Built-in Google Analytics support

The module partially supports a built-in Magento Google Analytics module, namely:

  • Google Analytics executes when a user agrees to all cookie categories by clicking the “Allow All” button.
  • If you enable the Cookie Consent extension only for certain countries, Google Analytics executes after a customer allows cookies. For other countries, the Google Analytics code will work without restrictions.

In order to block Google Analytics until a customer accepts cookies, you should use one of the following solutions:

Option 1. Using Google Tag Manager

First, add your Google Analytics to Google Tag Manager. Then go to your Magento Admin Panel and configure Google Tag Manager in Cookie Consent Extension.

Go to the Edit Cookie Category page in the backend and insert your Google Analytics tag in the Head Scripts field.

Option 3. Customizing GA Built-In Support

Step 1. Create the following js file in your theme folder.

app/design/<Vendor>/<theme>/Magento_GoogleAnalytics/web/js/google-analytics.js

Step 2. Paste the following code into the created file.

In the example below, Google Analytics executes when a customer accepts the Statistics cookie category. If you want Google Analytics to execute when a customer accepts another cookie category, change the ‘statistics’ key in the following code to the relevant category key.

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
/* jscs:disable */
/* eslint-disable */
define([
    'jquery',
    'prCookieConsentApi',
    'domReady!'
], function ($, prCookieConsentApi) {
    'use strict';

    /**
     * @param {Object} config
     */
    return function (config) {
        if (prCookieConsentApi.isAllowedCategory('statistics')) {
            (function (i, s, o, g, r, a, m) {
                i.GoogleAnalyticsObject = r;
                i[r] = i[r] || function () {
                    (i[r].q = i[r].q || []).push(arguments)
                }, i[r].l = 1 * new Date();
                a = s.createElement(o),
                    m = s.getElementsByTagName(o)[0];
                a.async = 1;
                a.src = g;
                m.parentNode.insertBefore(a, m)
            })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

            // Process page info
            ga('create', config.pageTrackingData.accountId, 'auto');

            if (config.pageTrackingData.isAnonymizedIpActive) {
                ga('set', 'anonymizeIp', true);
            }

            // Process orders data
            if (config.ordersTrackingData.hasOwnProperty('currency')) {
                ga('require', 'ec', 'ec.js');

                ga('set', 'currencyCode', config.ordersTrackingData.currency);

                // Collect product data for GA
                if (config.ordersTrackingData.products) {
                    $.each(config.ordersTrackingData.products, function (index, value) {
                        ga('ec:addProduct', value);
                    });
                }

                // Collect orders data for GA
                if (config.ordersTrackingData.orders) {
                    $.each(config.ordersTrackingData.orders, function (index, value) {
                        ga('ec:setAction', 'purchase', value);
                    });
                }

                ga('send', 'pageview');
            } else {
                // Process Data if not orders
                ga('send', 'pageview' + config.pageTrackingData.optPageUrl);
            }
        }
    }
});

Was this article helpful?