How to Setup Data Layer on Shopify with GA4 Schema?

Step-01: After Login into Shopify Admin Panel –

Settings —-> Checkout —-> Scripts (Order status page scripts)

Step-02: Put the below code inside Scripts

{% if first_time_accessed %}

<script>
(function(dataLayer){

	var customer_type = ({{customer.orders_count}} > 1) ? 'repeatcustomer' : 'newcustomer';
	var discounts = "{{ order.discounts | map: 'code' | join: ',' | upcase}}";

	function strip(text){
    	return text.replace(/\s+/, ' ').replace(/^\s+/, '').replace(/\s+$/, '');
	}

	function firstof(){
    	for(var i = 0; i < arguments.length; i++){
        	if(arguments[i]) return arguments[i];
    	}
    	return null;
	}

	var products = [];
	{% for line_item in order.line_items %}
	products.push({
    	'id': firstof(strip('{{line_item.sku}}'), strip('{{line_item.product_id}}')),
    	'name': strip('{{line_item.product.title}}'),
    	'category': strip('{{line_item.product.type}}'),
    	'brand': strip('{{line_item.vendor}}'),
    	'variant': strip('{{line_item.variant.title}}'),
    	'coupon': "{{ line_item.discounts | map : 'code' | join: ',' | upcase}}",
    	'price': {{line_item.price | times: 0.01}},
    	'quantity': {{line_item.quantity}}
	});
	{% endfor %}

	dataLayer.push({
    	'event': 'purchase',
    	'customerType': customer_type,
    	'ecommerce': {
        	'currency': '{{shop.currency}}',
        	'transaction_id': '{{order.order_number}}',
        	'affiliation': strip('Shopify {{shop.name}}'),
        	'value': {{order.total_price | times: 0.01}},
        	'tax': {{order.tax_price | times: 0.01}},
        	'shipping': {{order.shipping_price | times: 0.01}},
        	'coupon': discounts,
        	'items': products
    	}
	});

	setTimeout(function(){
    	// Clear the ecommerce data for subsequent hits.
    	dataLayer.push({ 'ecommerce': null });
	}, 3);

}(window.dataLayer = window.dataLayer || []));
</script>
{% endif %}


<script>
function containsGTMStart(dl){
	var i = 0;
	dl.map(function(e){ if('gtm.start' in e) i++; });
	return !!i;
}
(function(w,d,s,l,i){
	w[l]=w[l]||[];
	// attempts to prevent GTM from loading twice.
	if(containsGTMStart(w[l])) return false;
	w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});
	var f=d.getElementsByTagName(s)[0],
    	j=d.createElement(s),
    	dl=l!='dataLayer'?'&l='+l:'';
	j.async=true;
	j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;
	f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-M9BTLDJ');
</script>

Step-04: Finally Check Data layer is working or not

Datalayer passing the values to the Tags. In another blog, I will discuss how to set up tags perfectly.

You can follow another way as well to setup the data layers. You can follow the below content.

This will send your product-level information to the data layer. All you need to do is just copy the code and paste it into your theme.liquid file and follow the steps below carefully.

If you are familiar with Google Tag Manager or our course, you should be able to use this with ease.

We need to edit your theme files. You can copy your existing theme and work on a duplicated theme if you like. Technically there is no reason for this as Shopify already saves the change history – so all the changes are actually risk-free.

Code block:

{% comment %} Product view data layer v2.0 - part of "Shopify GA4 Kit" by Analyzify
Visit https://analyzify.app/shopify-google-analytics/ga4 for complete tutorial 
{% endcomment %}

<script type="text/javascript">
  window.dataLayer = window.dataLayer || [];

  window.appStart = function(){
    {% assign template_name = template.name %} 

    window.productPageHandle = function(){
      var productName = "{{ product.title | remove: "'" | remove: '"' }}";
      var productId = "{{ product.id }}";
      var productPrice = "{{ product.price | money_without_currency }}";
      var productBrand = "{{ product.vendor | remove: "'" | remove: '"' }}";
      var productCollection = "{{ product.collections.first.title | remove: "'" | remove: '"' }}"

      window.dataLayer.push({
        event: 'analyzify_productDetail',
        productName: productName,
        productId: productId,
        productPrice: productPrice,
        productBrand: productBrand,
        productCategory: productCollection,
      });
    };

    {% case template_name %}
    {% when 'product' %}
    	productPageHandle()
    {% endcase %}
  }

  appStart();
</script>

Step 1: Edit the Shopify theme

We will add a new snippet into your theme to make it easier to manage. Go to Shopify Admin > Online Store > Themes > Choose Live Theme > Actions > Edit Code.

Step 2: Add new snippet

Scroll down to the “Snippets” section and click “Add new snippet” and name it “analyzify-product-datalayer” and CREATE.

Step 3: Paste the code

Paste the code you copied above into this newly created snippet file and SAVE.

Step 4: Include the snippet

Find theme.liquid file under the “Layout” section on the left bar. Open the theme.liquid file and search “/head” in the file. Paste the following code just above it:
{% render ‘analyzify-product-datalayer.liquid’ %}
At the final, it should look like in the screenshot.

Step 5: GTM Actions

Your Shopify product view data layer is ready to be processed. You can now go to Google Tag Manager and create the trigger for “analyzify_productDetail” event and create data layer variables for “name, id, price, currency, sku, category, variant_id” – just like we did in the above section for the purchase data layer.

Alternatively, you can follow our detailed GTM Tutorial on the product data layer and learn how it is used in-depth.

Write a Comment

Your email address will not be published.