Forum Replies Created

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter soorta

    (@soorta)

    UPDATE – SOLVED

    Just to clarify: I am not using Elementor for the product listing or add-to-cart buttons. Elementor is only used as a page builder for some parts of the website. The WooCommerce product output is customized through my child theme using WooCommerce hooks.

    I also tested this by removing my custom hooks and switching to another theme, but the AJAX AddToCart event still was not tracked properly in GTM.

    The issue was solved by adding a small GTM Custom HTML tag that listens to the standard WooCommerce added_to_cart event and pushes the CAPI Suite mcapi-atc-datalayer payload from the AJAX fragments into the dataLayer.

    For anyone with the same issue, here is the fix:

    1. In GTM, create a new tag:
    • Tag type: Custom HTML
    • Trigger: All Pages
    1. Add this code:
    <script>
    (function() {
      window.dataLayer = window.dataLayer || [];
      window.__mcapi_atc_pushed = window.__mcapi_atc_pushed || {};
    
      function onReady(callback) {
        if (window.jQuery) {
          callback(window.jQuery);
        } else {
          setTimeout(function() {
            onReady(callback);
          }, 100);
        }
      }
    
      onReady(function($) {
        $(document.body).on('added_to_cart', function(event, fragments, cart_hash, $button) {
          if (!fragments) {
            return;
          }
    
          var fragmentHtml = fragments['div.mcapi-atc-datalayer'];
    
          if (!fragmentHtml) {
            console.log('[MCAPI ATC Fix] No mcapi-atc-datalayer fragment found.');
            return;
          }
    
          try {
            var $fragment = $('<div>').html(fragmentHtml);
            var payloadRaw = $fragment.find('.mcapi-atc-datalayer').attr('data-mcapi-payload');
    
            if (!payloadRaw) {
              console.log('[MCAPI ATC Fix] Fragment found, but no data-mcapi-payload attribute.');
              return;
            }
    
            var payload = JSON.parse(payloadRaw);
    
            if (payload.event_id && window.__mcapi_atc_pushed[payload.event_id]) {
              console.log('[MCAPI ATC Fix] Duplicate AddToCart skipped:', payload.event_id);
              return;
            }
    
            if (payload.event_id) {
              window.__mcapi_atc_pushed[payload.event_id] = true;
            }
    
            window.dataLayer.push(payload);
    
            console.log('[MCAPI ATC Fix] AddToCart pushed to dataLayer:', payload);
          } catch (e) {
            console.warn('[MCAPI ATC Fix] Failed to parse/push AddToCart payload:', e);
          }
        });
      });
    })();
    </script>
    

    After adding this tag, the AJAX AddToCart event started appearing correctly in GTM/dataLayer.

    Thread Starter soorta

    (@soorta)

Viewing 2 replies - 1 through 2 (of 2 total)