Skip to content

Tracking & Consent

Commerce Connect includes a comprehensive e-commerce tracking system with built-in GDPR consent management. Track customer behavior across your storefront while respecting privacy regulations and customer preferences.

The tracking system consists of two independent components:

  1. Event Tracking - Fires e-commerce events to analytics providers (GA4, GTM, custom adapters)
  2. Consent Management - Controls when tracking events are allowed to fire (GDPR compliance)

These work independently: tracking fires events, consent gates those events. You can use tracking without consent (if GDPR doesn’t apply) or implement consent without tracking (using a third-party analytics system).

flowchart TD
WP["WordPress® JS Hooks\ncommerce-connect.product.* · commerce-connect.cart.*"]
tracking["tracking.ts\nMaps hooks → commerceConnectEvents"]
bus["window.commerceConnectEvents\nEvent Bus"]
gtm["window.dataLayer\nGTM pickup"]
ga4["commerce-connect-ga4-adapter.ts\nGA4 Provider"]
gtag["window.gtag()\nGoogle Analytics"]
consentState["commerce-connect-consent-state.ts\nCookie · canTrack filter"]
bannerUI["commerce-connect-banner.ts\nBanner + Modal UI"]
cookie["commerce_connect_consent\nCookie"]
user["Visitor"]
WP --> tracking
tracking --> bus
bus --> gtm
bus --> ga4
ga4 --> gtag
user -->|Accept / Reject| bannerUI
bannerUI -->|grant| consentState
consentState --> cookie
consentState -->|commerce-connect.tracking.canTrack| tracking
consentState -->|commerce-connect.consent.updated| ga4
style bus fill:#4f46e5,color:#fff
style consentState fill:#0891b2,color:#fff
style ga4 fill:#16a34a,color:#fff

Commerce Connect fires the following e-commerce events:

EventTriggerPayload
commerce_connect_v1_product_page_viewedCustomer views product pageProduct ID, name, price, category
commerce_connect_v1_product_category_viewedCustomer views category/shop pageProduct IDs, category, list name
commerce_connect_v1_search_performedCustomer searches productsSearch query, result count
commerce_connect_v1_product_selectedCustomer clicks product linkProduct ID, list name
EventTriggerPayload
commerce_connect_v1_cart_viewedCustomer views cartCart ID, items, subtotal
commerce_connect_v1_cart_product_addedCustomer adds item to cartProduct ID, quantity, price
commerce_connect_v1_cart_product_removedCustomer removes itemProduct ID, quantity
commerce_connect_v1_begin_checkoutCustomer clicks checkoutCart ID, items, total

All events flow through window.commerceConnectEvents, a centralized event bus with typed channels:

// Subscribe to product page views
window.commerceConnectEvents.product.pageViewed((payload) => {
console.log('Product viewed:', payload);
// payload: { event_id, currency, product_value, line_items }
});
// Subscribe to cart additions
window.commerceConnectEvents.cart.addItem((payload) => {
console.log('Item added to cart:', payload);
// payload: { event_id, currency, cart_value, line_items }
});
// Subscribe to checkout events
window.commerceConnectEvents.checkout.checkoutBegin((payload) => {
console.log('Checkout started:', payload);
// payload: { event_id, currency, cart_value, line_items }
});

The event bus also pushes events to window.dataLayer for GTM pickup.

GA4 tracking is opt-in. Activate it by adding configuration to your theme:

// In your theme's footer or header
window.commerceConnectGA4Config = {
measurementId: 'G-XXXXXXXXXX', // Your GA4 measurement ID
consentMode: true, // Enable consent mode integration
};

Once configured, the GA4 adapter automatically sends e-commerce events to Google Analytics using the gtag() function.

Commerce Connect events map to GA4 e-commerce events:

Commerce Connect EventGA4 EventEnhanced Ecommerce
commerce_connect_v1_product_page_viewedview_item
commerce_connect_v1_product_category_viewedview_item_list
commerce_connect_v1_cart_product_addedadd_to_cart
commerce_connect_v1_cart_product_removedremove_from_cart
commerce_connect_v1_begin_checkoutbegin_checkout
commerce_connect_v1_search_performedsearch
commerce_connect_v1_product_selectedselect_item

Events automatically flow to window.dataLayer, making them available to GTM containers:

// Events pushed to dataLayer automatically
window.dataLayer = window.dataLayer || [];
dataLayer.push({
event: 'commerce_connect_v1_product_page_viewed',
ecommerce: {
items: [
{
item_id: '123',
item_name: 'Organic Cotton Throw',
price: 89.99,
item_category: 'Home Decor',
},
],
},
});

Configure GTM triggers to listen for these events and fire tags accordingly.

Create custom adapters to send events to other analytics providers:

// Example: Custom adapter for your analytics service
window.addEventListener('commerce-connect.tracking.event', (event) => {
const { detail } = event;
// Send to your analytics service
yourAnalyticsService.track(detail.event, detail.payload);
});

Commerce Connect includes a built-in GDPR consent banner that appears on first visit:

  • Cookie-based consent - Stores visitor’s choice in commerce_connect_consent cookie
  • Customizable messaging - Configure banner text via WordPress® filters
  • Accept/Reject options - Visitors can grant or deny tracking consent
  • Modal details - Detailed privacy information accessible from banner

The consent cookie stores visitor preferences as URL-encoded JSON:

{ "analytics": true, "marketing": false, "v": 1 }
  • analytics - Whether analytics/statistics tracking is permitted
  • marketing - Whether marketing/advertising tracking is permitted
  • v - Schema version (currently 1)

Cookie name: commerce_connect_consent (default, configurable)

Cookie expires after 365 days and respects GDPR requirements.

Access and manage consent state programmatically:

// Check consent status
const prefs = window.commerceConnectConsent.getPrefs();
const analyticsGranted = prefs?.analytics ?? false;
const marketingGranted = prefs?.marketing ?? false;
// Listen for consent changes
window.wp.hooks.addAction('commerce-connect.consent.updated', 'my-plugin', (consent) => {
const { analytics, marketing, source } = consent;
console.log('Consent updated:', { analytics, marketing, source });
// source: 'accept_all', 'reject_all', 'save_preferences', or 'page_load'
});
// Grant consent programmatically (e.g., from CMP)
window.commerceConnectConsent.grant({ analytics: true, marketing: false, v: 1 }, 'programmatic');

All tracking events pass through a consent filter before firing:

commerce-connect.tracking.canTrack
// Return false to block event, true to allow
window.wp.hooks.addFilter('commerce-connect.tracking.canTrack', 'my-cmp', (allowed, eventName) => {
const prefs = window.commerceConnectConsent.getPrefs();
const analytics = ['view_item', 'add_to_cart', 'view_cart', 'begin_checkout'];
// Block analytics events if consent denied
if (analytics.includes(eventName) && !prefs?.analytics) {
return false;
}
return allowed;
});

When GA4 tracking is enabled with consentMode: true, Commerce Connect automatically integrates with Google Consent Mode v2:

// Consent state automatically synced to gtag
gtag('consent', 'update', {
analytics_storage: 'granted', // or 'denied'
ad_storage: 'denied', // Always denied by Commerce Connect
ad_user_data: 'denied',
ad_personalization: 'denied',
});

This allows GA4 to respect consent preferences for analytics cookies while still collecting basic traffic data (consent mode modeling).

Section titled “Custom Consent Management Platforms (CMPs)”

Integrate Commerce Connect with third-party CMPs (OneTrust, Cookiebot, etc.):

// Example: OneTrust integration
function syncOneTrustConsent() {
const consent = OneTrust.GetDomainData().Groups.find((g) => g.GroupName === 'Performance Cookies');
const prefs = {
analytics: consent?.Status === 'active',
marketing: false,
v: 1,
};
window.commerceConnectConsent.grant(prefs, 'onetrust');
}
// Sync on page load and CMP changes
syncOneTrustConsent();
OneTrust.OnConsentChanged(() => syncOneTrustConsent());
  1. Enable GA4 Tracking

Add to your theme’s functions.php:

add_action('wp_footer', function() {
?>
<script>
window.commerceConnectGA4Config = {
measurementId: 'G-XXXXXXXXXX',
consentMode: true
};
</script>
<?php
});
  1. Customize Consent Banner (Optional)
// Customize banner text
add_filter('commerce_connect_consent_banner_text', function($text) {
return 'We use cookies to improve your shopping experience. Accept to continue.';
});
// Customize privacy policy link
add_filter('commerce_connect_consent_privacy_url', function($url) {
return get_permalink(get_privacy_policy_page_id());
});
  1. Test Tracking
  • Visit a product page (should fire product_viewed event)
  • Add product to cart (should fire product_added_to_cart event)
  • Check browser console for event logs (if debug mode enabled)
  • Verify events appear in GA4 real-time reports

If you’re using GTM to manage Google Analytics (instead of the GA4 adapter):

  1. Don’t set commerceConnectGA4Config - Events will only flow to dataLayer
  2. Configure GTM triggers - Listen for Commerce Connect events in dataLayer
  3. Create GA4 tags - Fire on Commerce Connect event triggers
  4. Test - Use GTM preview mode to verify events flow correctly

Implement a custom adapter for your analytics service:

// Add to your theme's footer
(function () {
function sendToAnalytics(event, payload) {
// Your analytics service API call
fetch('https://analytics.example.com/track', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ event, payload, timestamp: new Date() }),
});
}
// Listen for Commerce Connect events on the event bus
window.commerceConnectEvents.cart.addItem((payload) => {
const prefs = window.commerceConnectConsent.getPrefs();
if (prefs?.analytics) {
sendToAnalytics('cart_product_added', payload);
}
});
window.commerceConnectEvents.product.pageViewed((payload) => {
const prefs = window.commerceConnectConsent.getPrefs();
if (prefs?.analytics) {
sendToAnalytics('product_page_viewed', payload);
}
});
})();
// In browser console or add to theme footer
localStorage.setItem('commerce_connect_tracking_debug', 'true');
// Reload page - events will log to console

Open browser console and watch for event logs:

[Commerce Connect Tracking] Event: commerce_connect_v1_product_page_viewed
{
event_id: "550e8400-e29b-41d4-a716-446655440000",
currency: "USD",
product_value: 89.99,
line_items: [{
product_id: "123",
product_name: "Organic Cotton Throw",
base_price: 89.99,
category_names: ["Home Decor"],
quantity: 1
}]
}
// In browser console
const prefs = window.commerceConnectConsent.getPrefs();
console.log('Analytics consent:', prefs?.analytics);
console.log('Marketing consent:', prefs?.marketing);
// View consent cookie
document.cookie.split(';').find((c) => c.includes('commerce_connect_consent'));
// Returns: "commerce_connect_consent=%7B%22analytics%22%3Atrue%2C%22marketing%22%3Afalse%2C%22v%22%3A1%7D"
// (URL-encoded JSON)
  1. Open Google Analytics → Realtime report
  2. Visit a product page on your site
  3. Check for view_item event in real-time stream
  4. Verify event parameters (item_id, item_name, price)
  • Lazy loading - Tracking scripts load asynchronously after page content
  • Event batching - Multiple events bundled in single dataLayer push
  • No render blocking - Tracking doesn’t delay page rendering
  • Cached consent - Cookie check avoids repeated consent API calls
  • JavaScript bundle - ~15KB gzipped (tracking + consent)
  • HTTP requests - 0 additional requests (events use existing GA4/GTM tags)
  • Cookie storage - Single 20-byte consent cookie
  • localStorage - Debug flag only (when enabled)
  • Explicit consent - Banner requires active acceptance/rejection
  • Cookie disclosure - Privacy policy link in banner
  • Right to withdraw - Visitors can revoke consent anytime
  • Data minimization - Only essential product/cart data tracked
  • No PII - Customer emails/names not sent to analytics
  • Consent cookie - 365 days (1 year)
  • GA4 cookies - Managed by Google (default: 2 years, configurable)
  • Session cookies - Cleared on browser close

Commerce Connect does not store tracking data - all events flow to your chosen analytics provider. Configure data retention policies in your analytics platform (GA4, GTM, custom service).

    • Step-by-step setup walkthrough
    • Complete event payloads, hooks, settings
    • Build adapters for other providers
    • Privacy best practices