2

I have created a custom event and created a datalayer push into the template.liquid-file in my Shopify. I can get my custom event to fire in Tag Manager when I just view a product, so I know that the push works, but I need to trigger the push when a product is added to my Shopify cart, and I'm not sure it's even possible the way I'm trying to do it.

This is the code I currently have for the push:

{% if cart.item_count > 0 %}
  <script type="text/javascript" defer>
     window.dataLayer = window.dataLayer || []; 
     dataLayer.push({
       'event': 'addedToCart',
       'ecommerce': {
         'currencyCode': '{{ shop.currency }}',
         'add': {                                
           'products': [{                        
             'name': '{{ product.title }}',
             'id': {{ product.id }},
             'price': {{ product.price | divided_by: 100 }},
             'category': '{{ product.type }}',
             'variant': '{{ product.selected_or_first_available_variant }}',
             'quantity': '{{ product.quantity }}'
           }]
         }
       }
     });
     cart_data = {{ cart | json}};
     console.log(cart_data);
  </script>
{% endif %}

I'm trying to avoid triggering on button clicks, since there are many different buttons on the store, but if that's the only way around this, I will do it

csharpbd
  • 3,786
  • 4
  • 23
  • 32

1 Answers1

0

Go to Section/ product-template.liquid and add your data layer inside your add to cart button:

onclick="dataLayer.push({ 'ecommerce': null });dataLayer.push({
'event': 'addedToCart',
'ecommerce': {
    'currency': '{{ shop.currency }}',
    'items': [{
    'item_name': '{{ product.title | remove: "'" | remove: '"' }}',
    'item_id': '{{ product.id }}',
    'price': '{{ product.price  | times: 0.01}}',
    'item_category': '{{ product.collections[0].title | remove: "'" | remove: '"' }}',
    'item_variant': '{{ product.selected_variant.sku }}',
    'quantity': '{{ product.quantity }}'
    }]
}
});" 
  • Please do never recommend usanfe inline JavaScript!! Consult articles on the topic (there are many), you can also start here: https://stackoverflow.com/questions/11916151/why-are-inline-js-blocks-unsafe or here https://content-security-policy.com/unsafe-inline/ – jasie Aug 18 '22 at 12:06