Ad

Google Tag Manager Data Layer Variable Undefined - Shopify

- 1 answer

I'm using Shopify variables to try and push data through the Data Layer to use in Schema on particular pages. I used a Snippet to do this:

<!-- GTM Product Information via Data Layer -->

{% if product.url contains 'products' %}
{%- assign current_variant = product.selected_or_first_available_variant -%}
  <script>
   window.dataLayer = window.dataLayer || [];
   window.dataLayer.push({
      'gtm_product_url': '{{ product.url }}',
      'gtm_product_title' : '{{ product.title }}',
      'gtm_product_image' : '{{ product.featured_image }}',
      'gtm_product_description' : '{{ product.description | strip_html | strip_newlines | replace: '"', '' }}',
      'gtm_date' : '{{'now' | date: '%Y-%m-%d' }}',
      'gtm_sku' : '{{ current_variant.sku }}'
   });
  </script>
{% endif %}


{% if page.url contains 'pages' %}
  <script>
   window.dataLayer = window.dataLayer || [];
   window.dataLayer.push({
      'gtm_page_title': '{{ page.title }}',
      'gtm_page_published': {{ page.published_at }},
      'gtm_page_image' : {{ page_image | img_url }},
      'gtm_page_description' : {{ page_description }}
   });
  </script>
{% endif %}

I added the Variables in Google Tag Manager. The data shows up on the pages just fine (using the Shopify variables). And the product pages are actually pushing the data to GTM.

My problem is with the 'pages'. I see the data on the pages from Shopify and I've added the Variables into GTM, but they all show undefined when I try to add them to GTM.

I'm not sure what I'm doing wrong though. Any insights would be greatly appreciated!

Ad

Answer

You code works fine, but in case you had not noticed, you have not enclosed the values in quotes for the page section. You existing code without quotes throw

Uncaught SyntaxError: Unexpected token ':'

Wrapping quotes, it should work fine.

{% if page.url contains 'pages' %}
  <script>
   window.dataLayer = window.dataLayer || [];
   window.dataLayer.push({
      'gtm_page_title': "{{ page.title }}",
      'gtm_page_published': "{{ page.published_at }}",
      'gtm_page_image' : "{{ page_image | img_url }}",
      'gtm_page_description' : "{{ page_description }}"
   });
  </script>
{% endif %}

Moreover, console.log values for testing to see if you are receiving the expected values.

Ad
source: stackoverflow.com
Ad