Conversion Tracking and Dynamic Remarketing Tag instructions for Shopify

Improve your advertising effectiveness by setting up conversion tracking and dynamic remarketing tag on your Shopify website

  1. You will first need to import the FeedOps Google Tag Manager container on your website.
  2. Once Google Tag Manager has been set up, log in to your Shopify admin panel.
  3. In the left-hand menu, now go to Settings > Customer events. Click on Add custom pixel button at the top-right and enter the pixel name as FeedOps Pixel.Shopify-customer-event
4.    Please select the following options for Customer privacy:

Customer privacy

5.   Copy and paste the following script in the Code section.
Note: Replace GTM-XXXXXXX with your Google Tag Manager Container ID

(function (w, d, s, l, i) {
  w[l] = w[l] || [];
  w[l].push({ 'gtm.start': new Date().getTime(), 'event': 'gtm.js' });
  var f = d.getElementsByTagName(s)[0],
    j = d.createElement(s),
    dl = l !== 'dataLayer' ? '&l=' + l : '';
  j.async = true;
  j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl;
  f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-XXXXXXXX');

// set your product id values are default, product_id, parent_id, sku
// 1. If it looks like shopify_US_81191654332_1055121650148, then keep dc_product_id set to default
// 2. If it looks like 1055121650148 then set the value dc_product_id to product_id
// 3. If it looks like the main id 81191654332 then set the value dc_product_id to parent_id
// 4. If it looks like a sku then set the value dc_product_id to sku

let dc_product_id = 'default';

// Please add your alpha2 code, you can find it here: https://help.shopify.com/en/api/custom-storefronts/storefront-api/reference/enum/countrycode

let dc_product_id_alpha2_code = 'AU';

// Please add your shop currency code
let shop_currency_code = 'AUD';

//  CODE SETTINGS END
// ------------------------------------
//  DO NOT EDIT ANYTHING BELOW THIS LINE

// Utility function to safely extract nested values
function getNestedValue(obj, path, defaultValue = '') {
  return path
    .split('.')
    .reduce((acc, part) => (acc && acc[part] ? acc[part] : defaultValue), obj);
}

// Function to generate ecomm_prodid dynamically
function getEcommProdId(product, variant) {
  if (dc_product_id == 'default') {
    return `shopify_${dc_product_id_alpha2_code}_${product.id}_${variant.id}`;
  } else if (dc_product_id == 'product_id') {
    return `${variant.id}`;
  } else if (dc_product_id == 'parent_id') {
    return `${product.id}`;
  } else if (dc_product_id == 'sku') {
    return `${variant.sku}`;
  }
}

// Function to push event data to dataLayer
function pushToDataLayer(eventData) {
  window.dataLayer = window.dataLayer || [];
  window.dataLayer.push(eventData);
}

// Page view event
analytics.subscribe('page_viewed', (event) => {
  const baseUrl = event.context.document.location.pathname;
  const pageType = baseUrl === '/' ? 'home' : null;
  if (pageType) {
    pushToDataLayer({
      event: 'DynamicRemarketing',
      ecomm_pagetype: pageType,
      currency: shop_currency_code,
    });
  }
});

// Product viewed event
analytics.subscribe('product_viewed', (event) => {
  const product = getNestedValue(event.data, 'productVariant.product');
  const variant = getNestedValue(event.data, 'productVariant');

    const productPrice = variant.price.amount;
    const currencyCode = variant.price.currencyCode;
    const ecomm_Id = getEcommProdId(product, variant);
    pushToDataLayer({
      event: 'DynamicRemarketing',
      ecomm_pagetype: 'product',
      currency: currencyCode,
      ecomm_totalvalue: productPrice,
      ecomm_prodid: [ecomm_Id],
    });

});

// Collection viewed event
analytics.subscribe('collection_viewed', (event) => {
  const collectionTitle = getNestedValue(event.data, 'collection.title');
console.log(event)
  pushToDataLayer({
    event: 'DynamicRemarketing',
    ecomm_pagetype: 'category',
    currency: shop_currency_code,
  });
  
});

// Product added to cart event
analytics.subscribe('product_added_to_cart', (event) => {
    const cartLine = getNestedValue(event.data, 'cartLine');
    const product = getNestedValue(cartLine, 'merchandise.product');
    const cartLineCost = getNestedValue(cartLine, 'cost.totalAmount.amount');
    const cartLineCostCurrency = getNestedValue(
      cartLine,
      'cost.totalAmount.currencyCode'
    );
    const ecomm_Id = getEcommProdId(product, cartLine.merchandise);

    pushToDataLayer({
      event: 'DynamicRemarketing',
      ecomm_pagetype: 'cart',
      ecomm_totalvalue: cartLineCost,
      currency: cartLineCostCurrency,
      ecomm_prodid: [ecomm_Id],
    });

});

// Search submitted event
analytics.subscribe('search_submitted', (event) => {
  
  pushToDataLayer({
    event: 'DynamicRemarketing',
    ecomm_pagetype: 'searchresults',
    currency: shop_currency_code,
  });
});

// Checkout completed event
analytics.subscribe('checkout_completed', (event) => {
  const checkout = getNestedValue(event.data, 'checkout');

  if (checkout) {
    const user_phone =
      checkout.billingAddress?.phone ||
      checkout.shippingAddress?.phone ||
      checkout.phone;
    const user_first_name =
      checkout.billingAddress?.firstName || checkout.shippingAddress?.firstName;
    const user_last_name =
      checkout.billingAddress?.lastName || checkout.shippingAddress?.lastName;
    const order_city =
      checkout.shippingAddress?.city || checkout.billingAddress?.city;
    const order_region =
      checkout.shippingAddress?.province || checkout.billingAddress?.province;
    const order_postal_code =
      checkout.shippingAddress?.zip || checkout.billingAddress?.zip;
    const order_country_code =
      checkout.shippingAddress?.countryCode ||
      checkout.billingAddress?.countryCode;

    const ecomm_prodid = checkout.lineItems.map((item) =>
      getEcommProdId(item.variant.product, item.variant)
    );
    
    pushToDataLayer({
      event: 'DynamicRemarketing',
      ecomm_pagetype: 'purchase',
      ecomm_totalvalue: checkout.totalPrice.amount,
      order_id: checkout.order.id,
      currency: checkout.currencyCode,
      user_email: checkout.email,
      user_phone: user_phone,
      order_user_first_name: user_first_name,
      order_user_last_name: user_last_name,
      order_shipping_city: order_city,
      order_shipping_region: order_region,
      order_shipping_postal_code: order_postal_code,
      order_shipping_country_code: order_country_code,
      ecomm_prodid: ecomm_prodid,
    });
  }
});

To verify that your Dynamic Remarketing and Conversion Tracking works, you can follow Test Dynamic Remarketing Tags & ConversionTracking Test Transaction guides.