Magento – Magento 2 Google Universal Analytics code

google analyticsmagento2

In a Magento 2.1.2 store under Stores -> Configuration -> Sales -> Google Api I entered the Google Analytics code. After a couple of days I noticed no information coming in and my customer had a mail from Google saying the URL was no longer valid for the Merchant account.

I found that my customer had a Universal Analytics code (compared to the "old analytics code" and that Google demands it to be within the < head > tags whereas Magento 2.1.2 places it within the < body > tag. This Universal Analytics code has been around for 4 years and even with the old code it was recommended to place it within the < head > tags.

My question is, why is it that even in Magento 2 the Google Analytics code is placed within the body tags? Is there a good reason for it or am I missing something?

Best Answer

I hope you have found the answer to it, if not here is a simplest solution to it

In you theme add directory Magento_GoogleAnalytics > layout.

Magento_GoogleAnalytics is Google Analytics module by Magento team.

It will then look like this
<MagentoBase>/app/design/frontend/<Vendor>/<theme>/Magento_GoogleAnalytics/layout

then create a layout file default.xml on above path

It will finally look like this
<MagentoBase>/app/design/frontend/<Vendor>/<theme>/Magento_GoogleAnalytics/layout/default.xml

Place the code in default.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <move element="google_analytics" destination="head.additional"/>
    </body>
</page>

In the above code we are moving the google analytics section in head using -

<move element="google_analytics" destination="head.additional"/>

Hope others looking for this find it useful.

Related Topic