Commit 39fa5eb2591 for woocommerce
commit 39fa5eb25915f4cb57d985668a783dcb24d4580c
Author: Chi-Hsuan Huang <chihsuan.tw@gmail.com>
Date: Wed Nov 18 11:11:31 2026 +0800
Fix analytics still tracking shoppers who denied statistics consent (#70846)
* Stop tracking shoppers who denied statistics without a consent type
* Make the stored consent tests catch an allow treated as a deny
* Add changelog entry for the stored statistics deny fix
* Read a stored statistics deny before a delayed consent script loads
The client read the stored choice through the WP Consent API script's own globals, so a delay-JS plugin holding that script back skipped the check and tracking started. The page now names the statistics consent cookie, and the client reads it from document.cookie. The consent change listener is also set up, so consent given once the script loads is heard.
* Document how a stored statistics deny is handled by the speed module and delayed scripts
* Note that the speed module only reads the default consent cookie prefix
diff --git a/packages/php/woocommerce-analytics/README.md b/packages/php/woocommerce-analytics/README.md
index c97aa58fb6a..7942942dc9d 100644
--- a/packages/php/woocommerce-analytics/README.md
+++ b/packages/php/woocommerce-analytics/README.md
@@ -131,7 +131,7 @@ With WP Consent API active, `stats.wp.com/s-*.js`, which sets the `tk_*` referre
Withdrawing statistics consent expires the `tk_*` cookies on the page and drops events not yet sent. A page loaded with statistics consent denied expires any `tk_*` cookies left from an earlier visit.
-If an optimization plugin delays the WP Consent API script, for example until the visitor interacts with the page, nothing is tracked until that script loads and reports statistics consent, and a visit where it never loads is not tracked. This applies when a consent plugin sets a consent type through `wp_get_consent_type` or sets it later in the browser through `wp_consent_api_waitfor_consent_hook`. Both are read into the cacheable page, so they must resolve to the same value for every request. A consent plugin that sets `window.wp_consent_type` only in JavaScript, without either filter, is not detected, and tracking starts before the delayed script loads.
+If an optimization plugin delays the WP Consent API script, for example until the visitor interacts with the page, nothing is tracked until that script loads and reports statistics consent, and a visit where it never loads is not tracked. This applies when a consent plugin sets a consent type through `wp_get_consent_type` or sets it later in the browser through `wp_consent_api_waitfor_consent_hook`. Both are read into the cacheable page, so they must resolve to the same value for every request. A consent plugin that sets `window.wp_consent_type` only in JavaScript, without either filter, is not detected, and tracking starts before the delayed script loads. Without a consent type, tracking also starts before the delayed script loads, unless the shopper's statistics consent cookie stores a deny.
When WP Consent API is not active, the package defaults to allowing all tracking to maintain backward compatibility.
@@ -299,7 +299,7 @@ When proxy tracking is enabled:
**Server-Side Optimizations:**
-The package includes an optional MU plugin (`woocommerce-analytics-proxy-speed-module.php`) that significantly improves proxy performance by only loading WooCommerce, WooCommerce Analytics, and Jetpack for proxy requests
+The package includes an optional MU plugin (`woocommerce-analytics-proxy-speed-module.php`) that significantly improves proxy performance by only loading WooCommerce, WooCommerce Analytics, and Jetpack for proxy requests. A request from a shopper whose statistics consent cookie stores a deny is left to the REST route, which applies the consent check. The module runs before regular plugins, so it only reads the default `wp_consent` cookie prefix or one set by an earlier MU-plugin.
### Debugging
diff --git a/packages/php/woocommerce-analytics/changelog/fix-stored-statistics-deny-without-consent-type b/packages/php/woocommerce-analytics/changelog/fix-stored-statistics-deny-without-consent-type
new file mode 100644
index 00000000000..40520bc82a9
--- /dev/null
+++ b/packages/php/woocommerce-analytics/changelog/fix-stored-statistics-deny-without-consent-type
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fixed
+
+Stop tracking shoppers who denied statistics consent when the consent plugin sets no consent type.
diff --git a/packages/php/woocommerce-analytics/src/class-consent-manager.php b/packages/php/woocommerce-analytics/src/class-consent-manager.php
index 777e931a1dc..f4c82842fad 100644
--- a/packages/php/woocommerce-analytics/src/class-consent-manager.php
+++ b/packages/php/woocommerce-analytics/src/class-consent-manager.php
@@ -73,18 +73,33 @@ class Consent_Manager {
}
/**
- * Check if the shopper denied statistics consent, as recorded in the WP Consent API consent cookie.
+ * Get the name of the WP Consent API cookie that stores the shopper's statistics choice, or an empty string without the WP Consent API.
*
- * @return bool
+ * @since 0.18.2
+ *
+ * @return string
*/
- private static function is_statistics_consent_denied() {
+ public static function get_statistics_consent_cookie_name() {
+ if ( ! self::is_consent_api_active() ) {
+ return '';
+ }
+
$prefix = apply_filters( 'wp_consent_cookie_prefix', 'wp_consent' ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Reads a WP Consent API filter.
if ( ! is_string( $prefix ) ) {
- return false;
+ return '';
}
- $cookie_name = $prefix . '_' . self::WP_CONSENT_API_STATISTICS_TYPE;
+ return $prefix . '_' . self::WP_CONSENT_API_STATISTICS_TYPE;
+ }
+
+ /**
+ * Check if the shopper denied statistics consent, as recorded in the WP Consent API consent cookie.
+ *
+ * @return bool
+ */
+ private static function is_statistics_consent_denied() {
+ $cookie_name = self::get_statistics_consent_cookie_name();
- return isset( $_COOKIE[ $cookie_name ] ) && 'deny' === $_COOKIE[ $cookie_name ];
+ return '' !== $cookie_name && isset( $_COOKIE[ $cookie_name ] ) && 'deny' === $_COOKIE[ $cookie_name ];
}
}
diff --git a/packages/php/woocommerce-analytics/src/class-universal.php b/packages/php/woocommerce-analytics/src/class-universal.php
index f02dc228353..276bc4913e3 100644
--- a/packages/php/woocommerce-analytics/src/class-universal.php
+++ b/packages/php/woocommerce-analytics/src/class-universal.php
@@ -117,6 +117,9 @@ class Universal {
// A delay-JS plugin can hold back the consent API script, so the client cannot rely on its functions to know it has to wait.
wcAnalytics.consentManaged = <?php echo Consent_Manager::is_consent_managed() ? 'true' : 'false'; ?>;
+ // Read in the browser even before a delayed consent API script loads.
+ wcAnalytics.statisticsConsentCookie = <?php echo wp_json_encode( Consent_Manager::get_statistics_consent_cookie_name(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
+
wcAnalytics.breadcrumbs = <?php echo wp_json_encode( $this->get_breadcrumb_titles(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?>;
// Page context flags.
diff --git a/packages/php/woocommerce-analytics/src/client/consent.ts b/packages/php/woocommerce-analytics/src/client/consent.ts
index eb9304a608b..17f19c44ff4 100644
--- a/packages/php/woocommerce-analytics/src/client/consent.ts
+++ b/packages/php/woocommerce-analytics/src/client/consent.ts
@@ -41,6 +41,12 @@ export class ConsentManager {
return false;
}
+ // Read before the script check, since a delay-JS plugin can hold the script back. Without a consent type, wp_has_consent() also ignores it.
+ if ( this.getStoredStatisticsChoice() === 'deny' ) {
+ debug( 'Statistics consent denied in the consent cookie' );
+ return false;
+ }
+
if ( ! this.isWpConsentApiAvailable() ) {
debug( 'WP Consent API not available, defaulting to true for backward compatibility' );
return true;
@@ -51,6 +57,22 @@ export class ConsentManager {
return hasConsent;
}
+ /**
+ * Get the shopper's statistics choice stored by the WP Consent API: `allow`, `deny`, or empty when none is stored.
+ *
+ * @return The stored choice
+ */
+ private getStoredStatisticsChoice(): string {
+ const name = window.wcAnalytics?.statisticsConsentCookie;
+ if ( ! name ) {
+ return '';
+ }
+
+ // Like the WP Consent API's own reader, the first cookie with this name wins.
+ const cookie = document.cookie.split( '; ' ).find( entry => entry.startsWith( `${ name }=` ) );
+ return cookie ? cookie.slice( name.length + 1 ) : '';
+ }
+
/**
* Run the callback once the WP Consent API script has loaded, or right away when there is no need to wait for it.
*
@@ -109,9 +131,12 @@ export class ConsentManager {
* Initialize the consent change listener if not already done
*/
private initializeConsentListener(): void {
+ // The statistics cookie name is only set with the WP Consent API active, whose script may load later.
if (
this.isListenerInitialized ||
- ( ! this.isWpConsentApiAvailable() && ! this.isWaitingForConsentApi() )
+ ( ! this.isWpConsentApiAvailable() &&
+ ! this.isWaitingForConsentApi() &&
+ ! window.wcAnalytics?.statisticsConsentCookie )
) {
return;
}
diff --git a/packages/php/woocommerce-analytics/src/client/test/consent.test.ts b/packages/php/woocommerce-analytics/src/client/test/consent.test.ts
index ebcbee45d89..ef70d257549 100644
--- a/packages/php/woocommerce-analytics/src/client/test/consent.test.ts
+++ b/packages/php/woocommerce-analytics/src/client/test/consent.test.ts
@@ -121,3 +121,89 @@ describe( 'ConsentManager with a delayed WP Consent API script', () => {
expect( callback ).toHaveBeenCalledTimes( 1 );
} );
} );
+
+describe( 'ConsentManager.hasAnalyticsConsent with a stored statistics choice', () => {
+ const setStoredChoice = ( choice: string, name = 'wp_consent_statistics' ) => {
+ document.cookie = `${ name }=${ choice }; path=/`;
+ };
+
+ beforeEach( () => {
+ window.wcAnalytics = {
+ trackEndpoint: '',
+ eventQueue: [],
+ commonProps: {},
+ features: {},
+ pages: {},
+ assets_url: '',
+ consentManaged: false,
+ statisticsConsentCookie: 'wp_consent_statistics',
+ };
+ // Like the WP Consent API without a consent type: every category is granted.
+ window.wp_has_consent = () => true;
+ } );
+
+ afterEach( () => {
+ for ( const name of [ 'wp_consent_statistics', 'custom_statistics' ] ) {
+ document.cookie = `${ name }=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
+ }
+ delete window.wcAnalytics;
+ delete window.wp_has_consent;
+ } );
+
+ it( 'reports no consent when the shopper denied statistics, even though wp_has_consent() grants it', () => {
+ setStoredChoice( 'deny' );
+
+ expect( new ConsentManager().hasAnalyticsConsent() ).toBe( false );
+ } );
+
+ it( 'reports no consent when the shopper denied statistics before a delayed WP Consent API script loads', () => {
+ delete window.wp_has_consent;
+ setStoredChoice( 'deny' );
+
+ expect( new ConsentManager().hasAnalyticsConsent() ).toBe( false );
+ } );
+
+ it( 'reads the stored choice under the cookie name the page provides', () => {
+ window.wcAnalytics!.statisticsConsentCookie = 'custom_statistics';
+ setStoredChoice( 'deny', 'custom_statistics' );
+
+ expect( new ConsentManager().hasAnalyticsConsent() ).toBe( false );
+ } );
+
+ it( 'reports consent when the shopper allowed statistics and wp_has_consent() grants it', () => {
+ setStoredChoice( 'allow' );
+
+ expect( new ConsentManager().hasAnalyticsConsent() ).toBe( true );
+ } );
+
+ it( 'reports no consent when the shopper allowed statistics but wp_has_consent() refuses it', () => {
+ setStoredChoice( 'allow' );
+ window.wp_has_consent = () => false;
+
+ expect( new ConsentManager().hasAnalyticsConsent() ).toBe( false );
+ } );
+
+ it( 'reports consent when no choice is stored and wp_has_consent() grants it', () => {
+ expect( new ConsentManager().hasAnalyticsConsent() ).toBe( true );
+ } );
+
+ it( 'ignores a deny cookie when the page provides no cookie name, as without the WP Consent API', () => {
+ delete window.wp_has_consent;
+ window.wcAnalytics!.statisticsConsentCookie = '';
+ setStoredChoice( 'deny' );
+
+ expect( new ConsentManager().hasAnalyticsConsent() ).toBe( true );
+ } );
+
+ it( 'hears consent given once a delayed WP Consent API script loads', () => {
+ delete window.wp_has_consent;
+ const listener = jest.fn();
+
+ new ConsentManager().addConsentChangeListener( listener );
+ document.dispatchEvent(
+ new CustomEvent( 'wp_listen_for_consent_change', { detail: { statistics: 'allow' } } )
+ );
+
+ expect( listener ).toHaveBeenCalledWith( true );
+ } );
+} );
diff --git a/packages/php/woocommerce-analytics/src/client/types/global.d.ts b/packages/php/woocommerce-analytics/src/client/types/global.d.ts
index d6e69e592d6..898b1509424 100644
--- a/packages/php/woocommerce-analytics/src/client/types/global.d.ts
+++ b/packages/php/woocommerce-analytics/src/client/types/global.d.ts
@@ -13,6 +13,7 @@ declare global {
breadcrumbs?: string[];
assets_url: string;
consentManaged?: boolean;
+ statisticsConsentCookie?: string;
};
_wca?: {
push: ( props: Record< string, unknown > ) => void;
diff --git a/packages/php/woocommerce-analytics/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php b/packages/php/woocommerce-analytics/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php
index c90fc7081cf..969195295a1 100644
--- a/packages/php/woocommerce-analytics/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php
+++ b/packages/php/woocommerce-analytics/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php
@@ -47,6 +47,11 @@ class WooCommerceAnalyticsProxySpeed {
return;
}
+ // The WP Consent API has not loaded yet, so let the REST route apply the stored deny.
+ if ( $this->is_statistics_consent_denied() ) {
+ return;
+ }
+
// If autoloader failed, let WordPress continue loading
// and fallback to the regular REST API.
if ( ! $this->load_autoloader() ) {
@@ -94,6 +99,24 @@ class WooCommerceAnalyticsProxySpeed {
return substr( $normalized_path, -strlen( $proxy_suffix ) ) === $proxy_suffix;
}
+ /**
+ * Check if the shopper denied statistics consent, as recorded in the WP Consent API consent cookie.
+ *
+ * Unlike Consent_Manager, this reads the cookie whatever the consent type, which is not known yet. Only a prefix filter added by an earlier MU-plugin applies this early.
+ *
+ * @return bool
+ */
+ private function is_statistics_consent_denied() {
+ $prefix = apply_filters( 'wp_consent_cookie_prefix', 'wp_consent' ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingHookComment -- Reads a WP Consent API filter.
+ if ( ! is_string( $prefix ) ) {
+ return false;
+ }
+
+ $cookie_name = $prefix . '_statistics';
+
+ return isset( $_COOKIE[ $cookie_name ] ) && 'deny' === $_COOKIE[ $cookie_name ];
+ }
+
/**
* Load the autoloader.
*
diff --git a/packages/php/woocommerce-analytics/tests/php/Proxy_Speed_Module_Test.php b/packages/php/woocommerce-analytics/tests/php/Proxy_Speed_Module_Test.php
new file mode 100644
index 00000000000..51fd520620b
--- /dev/null
+++ b/packages/php/woocommerce-analytics/tests/php/Proxy_Speed_Module_Test.php
@@ -0,0 +1,126 @@
+<?php
+/**
+ * Tests for the proxy speed module MU-plugin template.
+ *
+ * @package automattic/woocommerce-analytics
+ */
+
+namespace Automattic\Woocommerce_Analytics;
+
+use WorDBless\BaseTestCase;
+
+/**
+ * Tests that the speed module leaves a shopper's stored statistics deny to the REST route.
+ */
+class Proxy_Speed_Module_Test extends BaseTestCase {
+
+ /**
+ * File error_log() writes to during a test.
+ *
+ * @var string
+ */
+ private $error_log_file;
+
+ /**
+ * Previous error_log ini value.
+ *
+ * @var string|false
+ */
+ private $previous_error_log;
+
+ /**
+ * Request globals as they were before the test.
+ *
+ * @var array
+ */
+ private $previous_server;
+
+ /**
+ * Load the template, whose own init() returns at load because the test request is not a proxy request.
+ */
+ public function set_up(): void {
+ parent::set_up();
+ require_once dirname( __DIR__, 2 ) . '/src/mu-plugin/woocommerce-analytics-proxy-speed-module-template.php';
+
+ $this->previous_server = $_SERVER;
+ $this->error_log_file = tempnam( sys_get_temp_dir(), 'wca-speed-module' );
+ $this->previous_error_log = ini_set( 'error_log', $this->error_log_file ); // phpcs:ignore WordPress.PHP.IniSet.Risky
+ }
+
+ /**
+ * Restore the request globals and error log.
+ */
+ public function tear_down(): void {
+ unset( $_COOKIE['wp_consent_statistics'], $_COOKIE['custom_statistics'] );
+ $_SERVER = $this->previous_server;
+ remove_all_filters( 'wp_consent_cookie_prefix' );
+ ini_set( 'error_log', (string) $this->previous_error_log ); // phpcs:ignore WordPress.PHP.IniSet.Risky
+ wp_delete_file( $this->error_log_file );
+ parent::tear_down();
+ }
+
+ /**
+ * Test that a proxy request carrying a stored deny returns before the module loads the package.
+ */
+ public function test_falls_through_to_the_rest_route_when_the_shopper_denied_statistics(): void {
+ $this->make_proxy_request();
+ $_COOKIE['wp_consent_statistics'] = 'deny';
+
+ ( new \WooCommerceAnalyticsProxySpeed() )->init();
+
+ $this->assertSame( '', file_get_contents( $this->error_log_file ) );
+ }
+
+ /**
+ * Test that a proxy request without a stored deny goes on to load the package.
+ *
+ * The template's autoloader placeholder is never replaced here, so loading it logs an error.
+ *
+ * @dataProvider provide_choices_the_module_still_serves
+ *
+ * @param string|null $choice The stored statistics choice, or null when none is stored.
+ */
+ public function test_goes_on_to_load_the_package_without_a_stored_deny( $choice ): void {
+ $this->make_proxy_request();
+ if ( null !== $choice ) {
+ $_COOKIE['wp_consent_statistics'] = $choice;
+ }
+
+ ( new \WooCommerceAnalyticsProxySpeed() )->init();
+
+ $this->assertStringContainsString( 'Autoloader path placeholder was not replaced', file_get_contents( $this->error_log_file ) );
+ }
+
+ /**
+ * Stored choices that do not deny statistics.
+ *
+ * @return array
+ */
+ public static function provide_choices_the_module_still_serves(): array {
+ return array(
+ 'no stored choice' => array( null ),
+ 'stored allow' => array( 'allow' ),
+ );
+ }
+
+ /**
+ * Test that the stored deny is read under a consent cookie prefix filtered by an MU-plugin that loads before the module.
+ */
+ public function test_falls_through_under_a_prefix_filtered_by_an_earlier_mu_plugin(): void {
+ $this->make_proxy_request();
+ add_filter( 'wp_consent_cookie_prefix', fn() => 'custom' );
+ $_COOKIE['custom_statistics'] = 'deny';
+
+ ( new \WooCommerceAnalyticsProxySpeed() )->init();
+
+ $this->assertSame( '', file_get_contents( $this->error_log_file ) );
+ }
+
+ /**
+ * Make the current request look like a proxy tracking request.
+ */
+ private function make_proxy_request(): void {
+ $_SERVER['REQUEST_METHOD'] = 'POST';
+ $_SERVER['REQUEST_URI'] = '/wp-json/woocommerce-analytics/v1/track';
+ }
+}
diff --git a/packages/php/woocommerce-analytics/tests/php/Universal_Page_Output_Test.php b/packages/php/woocommerce-analytics/tests/php/Universal_Page_Output_Test.php
index c911b3cd75c..eecb99d5891 100644
--- a/packages/php/woocommerce-analytics/tests/php/Universal_Page_Output_Test.php
+++ b/packages/php/woocommerce-analytics/tests/php/Universal_Page_Output_Test.php
@@ -381,6 +381,26 @@ class Universal_Page_Output_Test extends BaseTestCase {
$this->assertStringContainsString( 'wcAnalytics.consentManaged = true;', $this->render_analytics_data() );
}
+ /**
+ * Test that the page output gives the client no statistics cookie to read without the WP Consent API.
+ */
+ public function test_page_output_omits_the_statistics_consent_cookie_without_the_consent_api(): void {
+ $this->assertStringContainsString( 'wcAnalytics.statisticsConsentCookie = "";', $this->render_analytics_data() );
+ }
+
+ /**
+ * Test that the page output names the statistics cookie under a filtered prefix, so the client can read a deny before the consent API script loads.
+ *
+ * @runInSeparateProcess
+ * @preserveGlobalState disabled
+ */
+ public function test_page_output_names_the_statistics_consent_cookie_under_the_consent_cookie_prefix(): void {
+ require_once __DIR__ . '/mocks/wp-consent-api-functions.php';
+ add_filter( 'wp_consent_cookie_prefix', fn() => 'custom' );
+
+ $this->assertStringContainsString( 'wcAnalytics.statisticsConsentCookie = "custom_statistics";', $this->render_analytics_data() );
+ }
+
/**
* Test that the server-fired pixel path keeps its request-derived
* properties. That path runs on uncached requests and is the only place