google-analyticsshopifygoogle-tag-managergoogle-analytics-4google-datalayer

Google Analytics 4 ecommerce is not firing within Shopify theme


I have been updating our various websites to Google Analytics 4 over the past couple of months, and I've started working on the Shopify store. I've added an ecommerce dataLayer push in a liquid file within the Sections folder, but the dataLayer doesn't get updated. It's a simple view_item event, and I've checked and double-checked for typos. As a test, I replaced the ecommerce dataLayer push with a test_event with dummy data, which fired as expected.

Is there something I'm missing here? Why won't Shopify allow my ecommerce push to the dataLayer?

    dataLayer.push({ ecommerce: null });
    dataLayer.push({
        event: "view_item",
        ecommerce: {
            currency: {{ shop.currency }},
            value: {{ product.price | minus: discount.amount | money_without_currency }},
            items: [
                {
                    item_id: {{ product.id }},
                    item_name: {{ product.title }},
                    affiliation: "Shopify",
                    coupon: {{ discount.title }},
                    discount: {{ discount.amount | money_without_currency }},
                    index: 0,
                    item_category: "Products",
                    item_category2: {{ product.type }},
                    item_list_id: "related_products",
                    item_list_name: "Related Products",
                    price: {{ product.price | money_without_currency }},
                    quantity: 1
                }
            ]
        }
    });

I am using Google Tag Manager, but I can't get the dataLayer to update with the ecommerce event.


Solution

  • For anyone who might stumble onto this question, I believe I've found the issue. It's a simple case of syntax. The liquid variables which output strings need to be enclosed in quotes.

    I also added conditional statements to prevent some name-value pairs from appearing with no values.

    dataLayer.push({ ecommerce: null });
    dataLayer.push({
        event: 'view_item',
        ecommerce: {
            currency: '{{ shop.currency }}',
            value: {{ product.price | minus: discount.amount | money_without_currency }},
            items: [{
                item_id: '{{ product.id }}',
                item_name: '{{ product.title }}',
                affiliation: 'Shopify',
                {% if discount %}
                    coupon: '{{ discount.title }}',
                    discount: {{ discount.amount | money_without_currency }},
                {% endif %}
                index: 0,
                item_category: 'Products',
                {% if product.type %}
                    item_category2: '{{ product.type }}',
                {% endif %}
                price: {{ product.price | money_without_currency }},
                quantity: 1
            }]
        }
    });