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.
Overview
Section titled “Overview”The tracking system consists of two independent components:
- Event Tracking - Fires e-commerce events to analytics providers (GA4, GTM, custom adapters)
- 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).
Architecture
Section titled “Architecture”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:#fffEvent Tracking
Section titled “Event Tracking”Tracked Events
Section titled “Tracked Events”Commerce Connect fires the following e-commerce events:
Product Events
Section titled “Product Events”| Event | Trigger | Payload |
|---|---|---|
commerce_connect_v1_product_page_viewed | Customer views product page | Product ID, name, price, category |
commerce_connect_v1_product_category_viewed | Customer views category/shop page | Product IDs, category, list name |
commerce_connect_v1_search_performed | Customer searches products | Search query, result count |
commerce_connect_v1_product_selected | Customer clicks product link | Product ID, list name |
Cart Events
Section titled “Cart Events”| Event | Trigger | Payload |
|---|---|---|
commerce_connect_v1_cart_viewed | Customer views cart | Cart ID, items, subtotal |
commerce_connect_v1_cart_product_added | Customer adds item to cart | Product ID, quantity, price |
commerce_connect_v1_cart_product_removed | Customer removes item | Product ID, quantity |
commerce_connect_v1_begin_checkout | Customer clicks checkout | Cart ID, items, total |
Event Bus
Section titled “Event Bus”All events flow through window.commerceConnectEvents, a centralized event bus with typed channels:
// Subscribe to product page viewswindow.commerceConnectEvents.product.pageViewed((payload) => { console.log('Product viewed:', payload); // payload: { event_id, currency, product_value, line_items }});
// Subscribe to cart additionswindow.commerceConnectEvents.cart.addItem((payload) => { console.log('Item added to cart:', payload); // payload: { event_id, currency, cart_value, line_items }});
// Subscribe to checkout eventswindow.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.
Google Analytics 4 (GA4) Integration
Section titled “Google Analytics 4 (GA4) Integration”Enable GA4 Tracking
Section titled “Enable GA4 Tracking”GA4 tracking is opt-in. Activate it by adding configuration to your theme:
// In your theme's footer or headerwindow.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.
GA4 Event Mapping
Section titled “GA4 Event Mapping”Commerce Connect events map to GA4 e-commerce events:
| Commerce Connect Event | GA4 Event | Enhanced Ecommerce |
|---|---|---|
commerce_connect_v1_product_page_viewed | view_item | ✓ |
commerce_connect_v1_product_category_viewed | view_item_list | ✓ |
commerce_connect_v1_cart_product_added | add_to_cart | ✓ |
commerce_connect_v1_cart_product_removed | remove_from_cart | ✓ |
commerce_connect_v1_begin_checkout | begin_checkout | ✓ |
commerce_connect_v1_search_performed | search | ✓ |
commerce_connect_v1_product_selected | select_item | ✓ |
Google Tag Manager (GTM) Compatibility
Section titled “Google Tag Manager (GTM) Compatibility”Events automatically flow to window.dataLayer, making them available to GTM containers:
// Events pushed to dataLayer automaticallywindow.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.
Custom Analytics Adapters
Section titled “Custom Analytics Adapters”Create custom adapters to send events to other analytics providers:
// Example: Custom adapter for your analytics servicewindow.addEventListener('commerce-connect.tracking.event', (event) => { const { detail } = event;
// Send to your analytics service yourAnalyticsService.track(detail.event, detail.payload);});Consent Management
Section titled “Consent Management”Consent Banner
Section titled “Consent Banner”Commerce Connect includes a built-in GDPR consent banner that appears on first visit:
- Cookie-based consent - Stores visitor’s choice in
commerce_connect_consentcookie - 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
Cookie Format
Section titled “Cookie Format”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.
Consent State API
Section titled “Consent State API”Access and manage consent state programmatically:
// Check consent statusconst prefs = window.commerceConnectConsent.getPrefs();const analyticsGranted = prefs?.analytics ?? false;const marketingGranted = prefs?.marketing ?? false;
// Listen for consent changeswindow.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');Consent Filtering Hook
Section titled “Consent Filtering Hook”All tracking events pass through a consent filter before firing:
// 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;});Google Consent Mode v2
Section titled “Google Consent Mode v2”When GA4 tracking is enabled with consentMode: true, Commerce Connect automatically integrates with Google Consent Mode v2:
// Consent state automatically synced to gtaggtag('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).
Custom Consent Management Platforms (CMPs)
Section titled “Custom Consent Management Platforms (CMPs)”Integrate Commerce Connect with third-party CMPs (OneTrust, Cookiebot, etc.):
// Example: OneTrust integrationfunction 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 changessyncOneTrustConsent();OneTrust.OnConsentChanged(() => syncOneTrustConsent());Setup Guide
Section titled “Setup Guide”Basic Setup (GA4 + Consent Banner)
Section titled “Basic Setup (GA4 + Consent Banner)”- 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});- Customize Consent Banner (Optional)
// Customize banner textadd_filter('commerce_connect_consent_banner_text', function($text) { return 'We use cookies to improve your shopping experience. Accept to continue.';});
// Customize privacy policy linkadd_filter('commerce_connect_consent_privacy_url', function($url) { return get_permalink(get_privacy_policy_page_id());});- Test Tracking
- Visit a product page (should fire
product_viewedevent) - Add product to cart (should fire
product_added_to_cartevent) - Check browser console for event logs (if debug mode enabled)
- Verify events appear in GA4 real-time reports
GTM Setup (Without GA4 Adapter)
Section titled “GTM Setup (Without GA4 Adapter)”If you’re using GTM to manage Google Analytics (instead of the GA4 adapter):
- Don’t set
commerceConnectGA4Config- Events will only flow to dataLayer - Configure GTM triggers - Listen for Commerce Connect events in dataLayer
- Create GA4 tags - Fire on Commerce Connect event triggers
- Test - Use GTM preview mode to verify events flow correctly
Custom Analytics Setup
Section titled “Custom Analytics Setup”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); } });})();Debugging
Section titled “Debugging”Enable Debug Logging
Section titled “Enable Debug Logging”// In browser console or add to theme footerlocalStorage.setItem('commerce_connect_tracking_debug', 'true');
// Reload page - events will log to consoleVerify Events Fire
Section titled “Verify Events Fire”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 }]}Check Consent State
Section titled “Check Consent State”// In browser consoleconst prefs = window.commerceConnectConsent.getPrefs();console.log('Analytics consent:', prefs?.analytics);console.log('Marketing consent:', prefs?.marketing);
// View consent cookiedocument.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)Verify GA4 Integration
Section titled “Verify GA4 Integration”- Open Google Analytics → Realtime report
- Visit a product page on your site
- Check for
view_itemevent in real-time stream - Verify event parameters (item_id, item_name, price)
Performance
Section titled “Performance”Minimal Overhead
Section titled “Minimal Overhead”- 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
Resource Usage
Section titled “Resource Usage”- 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)
Privacy & Compliance
Section titled “Privacy & Compliance”GDPR Compliance
Section titled “GDPR Compliance”- 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
Cookie Lifespan
Section titled “Cookie Lifespan”- Consent cookie - 365 days (1 year)
- GA4 cookies - Managed by Google (default: 2 years, configurable)
- Session cookies - Cleared on browser close
Data Retention
Section titled “Data Retention”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).
Related Documentation
Section titled “Related Documentation”-
- Step-by-step setup walkthrough
-
- Complete event payloads, hooks, settings
-
- Build adapters for other providers
-
- Privacy best practices