Skip to content

[00] Subset Opt-Out, For developers

Developer reference

The PHP filters and actions, the window.subsetCM JavaScript API and events, the markup for holding your own scripts, and the WP-CLI commands.

This page lists Subset Opt-Out’s public API: PHP hooks, the JavaScript API and events, data attributes and WP-CLI commands. Anything not listed here, including every PHP class under Subset\CookieManager, is internal and may change.

Ground rules

  • Keep the HTML the same for every visitor. Pages are cached, so nothing you add may depend on the consent cookie, the current user, the request or the time. Per-visitor decisions happen in the browser.
  • Names. PHP prefix subset_cm, JavaScript global window.subsetCM, events subset-cm:<name>, cookie subset_cm_consent, attributes data-subset-cm-*.
  • Categories are fixed: functional (always allowed), statistics and marketing. You can’t add more.

window.subsetCM exists as soon as the inline head script has run, before any script WordPress prints after it.

MemberWhat it does
get()Returns a copy of the state: { v, source, categories: { functional, statistics, marketing } }. source is 'user', 'gpc' or null.
has( category )true if the category is allowed. functional is always true.
set( categories, source )Merges the categories over the current ones, writes the cookie and fires subset-cm:consent-changed.
optOut( source )Denies marketing, and statistics too if the site’s opt-out covers analytics.
optIn()Allows everything, as a user choice.
onChange( callback )Calls callback( detail ) on every change and returns an unsubscribe function. Added by the deferred bundle.
needsReloadtrue after a mid-session opt-out when scripts in a now-denied category had already run.
configThe parsed config block.
setRegime( regime )For add-ons. Sets the default regime ('optout' or 'optin') for this page view without recording a choice.

If the browser sends GPC, the API starts opted out with source gpc and writes the cookie. That applies when there’s no stored choice, and over a stored choice that allows something an opt-out denies, unless the visitor made that choice while GPC was on. A choice made with GPC on is stored with "gpc": true in the cookie, which get() doesn’t return.

// Run something only when marketing is allowed, now or later.
function whenMarketing(run) {
  if (window.subsetCM?.has("marketing")) return run();
  document.addEventListener("subset-cm:consent-changed", function handler() {
    if (window.subsetCM.has("marketing")) {
      document.removeEventListener("subset-cm:consent-changed", handler);
      run();
    }
  });
}

// Your own opt-out button.
document.querySelector("#my-opt-out").addEventListener("click", () => window.subsetCM.optOut());

Read subsetCM.get() when your script starts. Don’t cache the answer: a visitor can change their choice without a reload.

Events

Both events fire on document and bubble to window.

subset-cm:consent-changed fires whenever set, optOut or optIn changes the categories or the source. event.detail.consent is the new state and event.detail.previous is the old one. It doesn’t fire at page load, including for GPC. It also fires when setRegime() changes the default; then detail.consent.source is null, and code that records choices should ignore it.

subset-cm:reload-needed fires when needsReload turns true. event.detail.categories lists the denied categories whose scripts had already run.

document.addEventListener("subset-cm:reload-needed", () => {
  document.querySelector("#reload-note").hidden = false;
});

Hold your own scripts

Write a script as inert markup with a category, and Subset Opt-Out runs it when the visitor allows that category:

<script
  type="text/plain"
  data-subset-cm-category="marketing"
  src="https://ads.example/px.js"
  async
></script>

<script type="text/plain" data-subset-cm-category="statistics">
  myStats.track("pageview");
</script>
  • data-subset-cm-category is statistics, marketing or functional. Any other value never runs.
  • When allowed, the tag is replaced with a live copy in document order, keeping its other attributes. Add data-subset-cm-type="module" for a module script.
  • A held script with a src and no async finishes before the next held script starts.
  • To stop Subset Opt-Out holding a normal script, add data-subset-cm-ignore.
  • Scripts that already ran can’t be undone after a mid-session opt-out. Check subsetCM.needsReload.

Any element with data-subset-cm-open, or a link to #subset-cm-privacy-choices, opens the preferences panel:

<button type="button" data-subset-cm-open>Privacy choices</button>

Pages are cached, so don’t branch on consent in PHP when you build a page. Print held markup instead and let the browser decide. If your plugin uses the WP Consent API (opens in a new tab), Subset Opt-Out answers wp_has_consent() using this map:

WP Consent API categoryFollows
functionalfunctional
preferencesfunctional
statisticsstatistics
statistics-anonymousstatistics
marketingmarketing

Change the map with subset_cm_consent_categories.

PHP filters

FilterUse it to
subset_cm_servicesAdd, edit or remove service definitions. Built-ins are added at priority 5 and saved custom rules at 6.
subset_cm_blocking_rulesAdd custom blocking rules from code instead of the settings screen.
subset_cm_consent_categoriesChange how WP Consent API categories map to Subset Opt-Out’s.
subset_cm_frontend_configAdd data to the JSON config block that JavaScript reads as subsetCM.config.
subset_cm_blocking_appliesReturn false to switch blocking off for a request, such as a page builder preview.
subset_cm_blocking_bufferReturn false to skip the output-buffer pass that catches hard-coded scripts.
subset_cm_settings_defaults, subset_cm_sanitize_settingsAdd your own keys to the subset_cm_settings option.
subset_cm_settingsForce a setting from code, for example in an mu-plugin.
subset_cm_admin_tabsAdd tabs to Subset → Opt-Out. Print each panel with subset_cm_admin_panel_{slug}.
subset_cm_selectable_regimes, subset_cm_regimeLet the site use the optin regime, or force a regime site-wide.
subset_cm_datalayer_enabled, subset_cm_datalayer_nameTurn off the Tag Manager dataLayer events, or push them to a custom data layer.

Add a service

A service needs a label, a category (statistics or marketing) and at least one of src, inline or handles. cookies lists first-party cookies to delete on opt-out (a trailing * matches a prefix). extra.consent.revoke and extra.consent.grant name a function on window to call on opt-out and opt-in.

<?php
add_filter( 'subset_cm_services', function ( array $services ): array {
	$services['acme-ads'] = array(
		'label'    => 'Acme Ads',
		'category' => 'marketing',
		'src'      => array( 'cdn.acme-ads.example/px.js' ),
		'inline'   => array( 'acmeAds.init(' ),
		'cookies'  => array( '_acme_*' ),
		'extra'    => array(
			'consent' => array(
				'revoke' => array( 'fn' => 'acmeAds.consent', 'args' => array( 'revoke' ) ),
				'grant'  => array( 'fn' => 'acmeAds.consent', 'args' => array( 'grant' ) ),
			),
		),
	);
	unset( $services['x-pixel'] ); // Drop a built-in.
	return $services;
} );

The site owner can still switch your service off in the settings, and their choice wins.

Add a blocking rule

A rule is type (handle, url or inline), value (up to 200 characters) and category. Invalid rules and duplicates are dropped, and at most 100 are kept. Rules added in code don’t appear in the settings screen.

<?php
add_filter( 'subset_cm_blocking_rules', function ( array $rules ): array {
	$rules[] = array(
		'type'     => 'url',
		'value'    => 'widgets.acme.example/chat.js',
		'category' => 'marketing',
	);
	return $rules;
} );

Actions

ActionWhen it fires
subset_cm_loadingOn plugins_loaded, before any component registers. Add-ons hook in here.
subset_cm_settings_after_formAt the end of the Settings tab, after the plugin’s own forms.
subset_cm_admin_panel_{$slug}Prints the panel of a tab added with subset_cm_admin_tabs.
subset_cm_admin_enqueueOn Subset → Opt-Out, with the open tab’s slug. Enqueue your tab’s assets here.
subset_cm_bootedAfter every component has registered.
subset_cm_activatePer site, on activation.
subset_cm_deactivatePer site, on deactivation.
subset_cm_upgradeOn the first load after the version changes, with $from (or false) and $to.

Google Tag Manager events

Subset Opt-Out pushes two events to window.dataLayer:

  • subset_cm_consent_ready, once per page view with the visitor’s current state.
  • subset_cm_consent_update, every time the choice changes.

Both carry subset_cm: { functional, statistics, marketing, source }. Use them as Custom Event triggers to gate tags that aren’t Google tags, such as a pixel in a Custom HTML tag. Subset Opt-Out can’t hold tags that Tag Manager injects at run time. Google’s own tags follow Consent Mode.

WP-CLI

Every command lives under wp subset cookie-manager. WP-CLI commands lists each one with its options, defaults and examples, free and Pro.

Pro hooks

Subset Opt-Out Pro adds these filters:

FilterUse it to
subset_cm_pro_geo_providersAdd or remove the location headers Pro reads. Each entry is id => array( 'country' => …, 'region' => … ).
subset_cm_pro_geo_regionSupply the visitor’s region from somewhere else, such as a constant on a staging site.
subset_cm_pro_optout_log_rate_limitChange the opt-out log endpoint’s rate limit (20 requests a minute per client). 0 turns it off.
subset_cm_pro_client_ipGive the client IP the opt-out log uses, for sites behind a proxy.

Pro reads location from Cloudflare (CF-IPCountry, CF-Region-Code), CloudFront, Vercel and Netlify headers, GEOIP_* server variables, and the generic X-Geo-Country and X-Geo-Region headers.

Testing

Test that opting out works, not only that the link appears:

  1. Load a page in a fresh browser profile, open the preferences panel and opt out. Or turn on GPC in your browser.
  2. Open the network panel and reload.
  3. Check that no request goes to the trackers you’ve left on in Services to stop after an opt-out.

Get help

Report bugs and request features at Subset feedback on GitHub (opens in a new tab). For anything else, email hello@subsetwp.com.