Google Tag Manager Data Layer Variable Undefined - Shopify
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!
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.
Related Questions
- → Does anyone know how to solve IP canonicalization with shopify platform?
- → How can I add a featured image from a blog post to my homepage on shopify
- → Shopify - Get list of product from a specific collection
- → Shopify webhooks not wanted
- → Comparing two large files are taking over four hours
- → Need "add to cart" button price to update with correct amount depending on what checkbox is checked
- → How to append a variable inside another vaiable name in liquid html
- → GET /admin/webhooks.json returns an empty array
- → Javascript function not getting executed properly
- → How to give border to to current displaying border
- → Shopify background image
- → Dynamic Attribute Names in Shopify Cart
- → What after added shopify store into shipstation