Created
February 22, 2023 13:22
-
-
Save martinsoender/0fb4a5262c2757ad849d438d08e35dfc to your computer and use it in GitHub Desktop.
GTM - Add to cart event tracking for Shopify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!-- Example button element. Note class "product-add-to-cart" is not all button elements --> | |
| <button type="button" class="button button-green button-block product-add-to-cart">Add to cart</button> | |
| <script> | |
| // Global DataLayer declaration | |
| window.dataLayer = window.dataLayer || []; | |
| // Fetch all Add to cart button elements | |
| var AddToCartButtons = document.querySelectorAll('.<GLOBAL_ATC_BUTTON_CLASS>'); | |
| // Add event listener to each button element | |
| AddToCartButtons.array.forEach(addToCartButton => { | |
| // Listen to button click event | |
| addToCartButton.addEventListener('click', function(event) { | |
| window.dataLayer.push({ 'ecommerce': null }); | |
| // Push event info | |
| window.dataLayer.push({ | |
| 'event': 'add_to_cart', | |
| 'ecommerce': { | |
| 'items': [{ | |
| 'item_id': '{{ product.id }}', | |
| 'item_name': '{{ product.title | remove: "'" | remove: '"' }}', | |
| 'item_brand': '{{ product.vendor | remove: "'" | remove: '"' }}', | |
| 'item_category': '{{ product.collections[0].title | remove: "'" | remove: '"' }}', | |
| 'item_variant': '{{ product.selected_variant.sku }}', | |
| 'currency': '{{ shop.currency }}', | |
| 'price': '{{ product.price | times: 0.01}}' | |
| }] | |
| } | |
| }); | |
| }) | |
| }); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment