Search by

generoi / sage-cachetags

oxyc

Package info

github.com/generoi/sage-cachetags

pkg:composer/generoi/sage-cachetags

Statistics

Installs: 40 079

Dependents: 0

Suggesters: 0

Stars: 9

Open Issues: 0

v3.3.0 2026-11-16 19:42 UTC

README

A sage package for tracking what data rendered pages rely on using Cache Tags (inspired by Drupal's Cache Tags).

Example

Front page displays the page content as well as 3 recipe previews. The cache tags might be:

  • post:1 for the front page
  • post:232, post:233, post:234 for the 3 recipe previews
  • term:123, term:124 for a recipe category shown in the recipe previews
  • post:10 for a product name featured in one of the 3 recipes.

This set of tags will be gathered while rendering the page and then stored in the database and optionally added as a HTTP header.

When any of the posts or terms are updated, page caches and reverse proxies know that the front page cache should be cleared.

Installation

Composer

composer require generoi/sage-cachetags

Plugin

Download the zip, install like a regular plugin, then follow the standalone installation instructions below.

With Acorn (Sage theme)

Start by publishing the config/cachetags.php configuration file using Acorn:

wp acorn vendor:publish --provider="Genero\Sage\CacheTags\CacheTagsServiceProvider"

Edit it to your liking and if you're using the database store, scaffold the required database table:

wp acorn cachetags:database

Standalone (without Acorn)

For WordPress sites without Acorn, use the Bootstrap class in your theme's functions.php or a mu-plugin. The Bootstrap class provides a fluent interface for configuration:

use Genero\Sage\CacheTags\Bootstrap;
use Genero\Sage\CacheTags\Actions\Core;
use Genero\Sage\CacheTags\Actions\HttpHeader;
use Genero\Sage\CacheTags\Invalidators\SuperCacheInvalidator;
use Genero\Sage\CacheTags\Stores\WordpressDbStore;

// Bootstrap CacheTags using fluent interface
(new Bootstrap())
    ->store(WordpressDbStore::class)
    ->invalidators([SuperCacheInvalidator::class])
    ->actions([Core::class, HttpHeader::class])
    ->debug(defined('WP_DEBUG') && WP_DEBUG)
    ->httpHeader('Cache-Tag')
    ->bootstrap();

If you're using the database store, scaffold the required database table using WP-CLI:

wp cachetags database

Schema changes are migrated automatically on the next admin request after an update (the table version is tracked in the cachetags_db_version option). On headless or multisite setups, run wp cachetags database to apply migrations across all sites.

Invalidators

Currently it supports Kinsta Page Cache, WP Super Cache, SiteGround Optimizer, WP Rocket, Fastly and Cloudflare. You can use multiple invalidators if you eg use Fastly in front of Kinsta and want to invalidate both.

Coarse tags and bulk purges. A coarse tag like archive:post can resolve to many stored URLs (every page that lists posts), which URL-based invalidators must handle without firing thousands of individual purges, since those providers effectively rate-limit purges. They differ in how:

  • SiteGround (and similar) escalate to a full cache flush past a tunable threshold (cachetags/siteground-bulk-purge-threshold) — over-purging is safe when we can't know the exact URL set, though on a busy editorial site a single publish can flush the whole cache.
  • Kinsta instead routes bulk purges to its throttled endpoint, which coalesces them server-side — no full flush. The KinstaGroupCacheInvalidator (prefix purges) cuts the request count further; it's the recommended Kinsta setup.

Fastly is unaffected — it purges by Surrogate-Key, so URL count is irrelevant, which makes it the best fit for high-frequency editorial sites.

Stored URL and query strings

Front-end pages are stored under the actual requested URL (including its query string), so a URL-based purge matches the variant a page cache keyed on. A default set of tracking/volatile params (utm_*, gclid/fbclid/dclid/…, _wpnonce, _) is stripped and the rest sorted; a key longer than the varchar(191) column falls back to the path. The Kinsta invalidators also strip _ga, mc_cid, mc_eid and ref, which Kinsta's edge leaves out of its cache key and serves from the bare URL's entry; edges that cache them as their own key (SiteGround, WP Rocket, Super Cache) keep them.

On a query-bypass edge — Fastly (purges by Surrogate-Key, ignores the URL) or Kinsta (a query-string URL bypasses the cache, except for the params it leaves out of its cache key, which share the bare URL's entry) — those query-string rows are never cached and so never need purging; they just accumulate in the store (one row per visited ?… combination, including bot/scanner params). A query-bypass site with heavy parameterised traffic can keep the store lean by storing the path only:

add_filter('cachetags/store-query-string', '__return_false');

With query-string storage off (as KinstaGroupCacheInvalidator sets it), a render with a query string is stored under the bare URL, except one that renders differently from it: a search, a WordPress public query var (?p=, ?cat=, ?paged=, …) or a listing sort/filter (orderby, order, filter_*, min_price, fwp_*, …; extend with cachetags/render-params). Those aren't stored: /?s=x would otherwise give the front page every search result's tags, and purge it on every one of them, and Kinsta doesn't cache them. Any other param fails toward storing, since it renders the bare URL's page and the edge may serve it from the bare URL's entry. The tag header is sent either way.

add_filter('cachetags/render-params', fn (array $params) => [...$params, 'view']);

To match a URL-keyed edge that does cache query strings (SiteGround, or Kinsta configured to cache GET params) the strip list must equal that edge's — and that's site-specific (our own Fastly VCLs strip anywhere from 5 to 16 params), so align it per site:

add_filter('cachetags/url-ignored-params', fn ($p) => [...$p, 'campaign_id', 'tduid']);

Comprehensive query-param normalization is better done at the edge (CDN/VCL) than replicated here.

SiteGround Optimizer

Integration exists if you add the SiteGroundCacheInvalidator invalidator in the config/cachetags.php file.

When more than 50 URLs need purging, the invalidator performs a full cache flush instead of purging each URL individually. This avoids overwhelming SiteGround's cache API with thousands of synchronous requests. The threshold is configurable:

// Change the threshold (default: 50)
add_filter('cachetags/siteground-bulk-purge-threshold', fn () => 100);

// Always flush (never purge individual URLs)
add_filter('cachetags/siteground-bulk-purge-threshold', fn () => 0);

Super Cache

Integration exists if you add the SuperCacheInvalidator invalidator in the config/cachetags.php file.

Kinsta

Two invalidators, differing in how Kinsta resolves the purge:

  • KinstaGroupCacheInvalidator (recommended) purges by group| — a prefix wildcard that clears a path together with everything beneath it, such as its pagination (/shop/page/2/), in one request. It disables query-string storage (cachetags/store-query-string): on a standard Kinsta setup a query-string URL (/shop/?orderby=…) isn't cached at all, and the params Kinsta ignores (utm_*, …) are served from the bare path's entry, so the bare path is all there is to purge. This is the right choice for a standard Kinsta setup. Collapsing many URLs into a single prefix purge also keeps purge volume low — Kinsta dispatches purges to its edge (Cloudflare) asynchronously and rate- limits/coalesces them server-side, and the localhost endpoint returns 200 on accept (downstream throttling is invisible to the request), so fewer, coarser purges are the most effective way to stay under those limits. Bulk purges are additionally routed to Kinsta's throttled endpoint rather than a full flush.
  • KinstaCacheInvalidator purges by single| — the exact URL only. Use this if you've configured Kinsta to cache query-string URLs and need each variant purged by its full stored URL (see Stored URL and query strings).

Add one of them to the invalidator list in config/cachetags.php. The site root (/) is always purged exactly, so a group purge never flushes the whole site. So is each Polylang language home (pll_home_url(), e.g. /sv/), which would otherwise empty that whole language. Add other URLs whose prefix covers much of the site — a full URL matches its own host only, a path any host:

add_filter('cachetags/kinsta-exact-urls', fn (array $urls) => [...$urls, home_url('/shop/')]);

Cloudflare

CloudflareCacheInvalidator purges by cache tag using the Cache-Tag header. Cloudflare expects the tags comma-separated, so set the separator: ->httpHeader(['Cache-Tag' => ',']) (or 'http-header' => ['Cache-Tag' => ',']). Configure it with environment variables:

  • CLOUDFLARE_API_TOKEN — an API token with the Cache Purge permission on the zones.
  • CLOUDFLARE_ZONE_IDS — comma-separated zone IDs. Tags are per zone, so a site served on several domains (one zone each) lists them all, and every purge is sent to every zone.

Tags are sent 100 per request (Cloudflare's per-request maximum), with bounded concurrency. flush() purges everything in each zone, or the site tags when the Site action is active. A response only counts as a success on HTTP 200 with "success": true.

Soft purge. CloudflareSoftCacheInvalidator uses Cloudflare's invalidation instead: content is kept and marked stale, and with stale-while-revalidate the next visitor is served it while Cloudflare revalidates in the background — the equivalent of FastlySoftCacheInvalidator. Cloudflare ignores stale-while-revalidate and stale-if-error when s-maxage is present, so give the edge its own header without it; Cloudflare uses it instead of Cache-Control and doesn't pass it on to browsers:

Cloudflare-CDN-Cache-Control: max-age=604800, stale-while-revalidate=2592000, stale-if-error=2592000

Bulk purges. Above 500 tags (cachetags/cloudflare-bulk-purge-threshold) a purge flushes instead — one request per zone rather than one per 100 tags.

Rate limits. Tag purges are limited per account and shared by all zones on the same plan (limits): the Free plan allows 5 requests a minute with a burst of 25; Pro 5/s (burst 25), Business 10/s (burst 50). Each purge costs one request per zone per 100 tags, so a multi-domain site on Free runs out quickly. In WP-CLI and cron a rate-limited (429) purge is retried briefly (honouring Retry-After); a web request never waits, since purges run before the visitor's response is finished. Whatever is still limited goes into a per-zone DeferredQueue (cachetags_deferred_cloudflare:* options) and is retried by a single WP-cron event a minute later, coalesced, until it goes through. Make sure WP-cron runs on the site. Failures other than 429 are logged with error_log.

Genero\Sage\CacheTags\DeferredQueue is generic, for any invalidator whose API rate-limits (Kinsta and SiteGround do too): push(['key' => [...tags or URLs]]) or push(['key' => true]) for purge everything, hook a retry onto $queue->hook, and call $queue->take() there. Each push is its own option row, so concurrent requests can't overwrite each other's entries.

While migrating from Fastly, run both CDNs at once by emitting both headers:

(new Bootstrap)
    ->invalidators([KinstaCacheInvalidator::class, FastlySoftCacheInvalidator::class, CloudflareSoftCacheInvalidator::class])
    ->httpHeader(['Surrogate-Key' => ' ', 'Cache-Tag' => ','])
    // …
    ->bootstrap();

or 'http-header' => ['Surrogate-Key' => ' ', 'Cache-Tag' => ','] in config/cachetags.php. A header given without a separator — a plain string or a list entry — is space-separated. Cloudflare strips Cache-Tag before responding to visitors; Fastly does not strip Surrogate-Key unless your VCL does.

Fastly

There's both a FastlySoftCacheInvalidator and a FastlyCacheInvalidator (hard) cache invalidator for Fastly (Varnish) proxy cache. Using this set up you do not need a persistent store since Fastly works with HTTP headers. Example config/cachetags.php

$isProduction = in_array(parse_url(WP_HOME, PHP_URL_HOST), [
    'www.example.com',
]);

return [
    'http-header' => 'Surrogate-Key',
    'store' => CacheTagStore::class,
    'invalidator' => array_filter([
        $isProduction ? FastlySoftCacheInvalidator::class : null,
    ]),
    'action' => [
        Core::class,
        HttpHeader::class,
    ],
];

REST API integration

For headless/decoupled setups where pages are served from the WordPress REST API, enable the RestApi action to tag REST read responses so a frontend or CDN can purge them by cache tag:

use Genero\Sage\CacheTags\Actions\Core;
use Genero\Sage\CacheTags\Actions\HttpHeader;
use Genero\Sage\CacheTags\Actions\RestApi;

return [
    'http-header' => 'Cache-Tag',
    'action' => [
        Core::class,
        HttpHeader::class,
        RestApi::class,
    ],
];

Keep Core enabled alongside it: block-derived tags from content.rendered are still collected through Core's render_block hook during the REST request.

What gets tagged:

  • Single resources (/wp/v2/posts/123, /wp/v2/categories/5, /wp/v2/users/2, /wp/v2/comments/9) — the object itself, plus a post's related terms, author, featured media and parent.
  • Collections (/wp/v2/posts) — each item plus the relevant archive: / taxonomy: listing tag. The listing tag is added even for empty/filtered collections, so they refresh when their membership changes.
  • Search (/wp/v2/search) — each matched post/term.
  • Headless post types — public types plus any non-builtin post type/taxonomy exposed to REST (show_in_rest), so public=false content types are covered.

Only responses that may be publicly cached are tagged: requests are skipped when they are authenticated, use context=edit, carry a password, or are not GET/HEAD. The edge must strip the Cache-Tag header before it reaches clients.

Each response is stored under its canonical URL with sort-normalized query parameters, so variants that produce a different response — pagination/filters (?page=2, ?categories=5), context, and the server params that shape the body (_embed, _fields, _envelope, _locale) — get distinct, CDN-matching store keys and are purged separately. Parameters the route doesn't register (and aren't response-shaping) are dropped so arbitrary client params can't fork the key. Only the random per-request params _wpnonce and _ are stripped unconditionally — any cache entry keyed on them is never reused, so collapsing them can't cause staleness.

Custom routes

The RestApi action only knows about core wp/v2 objects. A custom public route that serves its own cacheable response (sets its own Cache-Control: public, s-maxage=…, e.g. my-plugin/v1/people) is cached at the edge but never purged unless it declares the cache tags its data depends on.

Do it the same way the front end does — add the tags while building the response, from the CacheTags instance (app(CacheTags::class) with Acorn, or CacheTags::getInstance() standalone). With RestApi/HttpHeader enabled they're emitted and stored on rest_post_dispatch:

public function handle(WP_REST_Request $request): WP_REST_Response
{
    $people = $this->search($request);

    CacheTags::getInstance()?->add([
        'archive:person',
        ...array_map(fn ($p) => "post:{$p->id}", $people),
    ]);

    return rest_ensure_response($people);
}

If the endpoint manages its own Cache-Control and you want full control, set the header yourself (and save() the URL for url-based purge):

$cacheTags->add($tags);
$cacheTags->save($request->get_route());
$response->header('Cache-Tag', implode(',', $tags));

Purge them from a small custom Action that hooks the relevant transition_post_status / meta / term events and calls $cacheTags->clear([...]), mirroring Core. (For a third-party route you can't edit, the cachetags/rest-tags filter below is the fallback.)

Filters

// Tag bespoke REST routes that don't map to a core object.
add_filter('cachetags/rest-tags', function (array $tags, WP_REST_Request $request) {
    return $request->get_route() === '/my-plugin/v1/feed'
        ? [...$tags, 'archive:post']
        : $tags;
}, 10, 2);

// Add or trim the related dependencies tagged for a post response.
// The matched WP_REST_Request is also passed as a third argument.
add_filter('cachetags/rest-related-tags', function (array $tags, WP_Post $post) {
    return $tags;
}, 10, 2);

// Change which query parameters are ignored when building the store URL.
add_filter('cachetags/rest-url-ignored-params', fn (array $params) => [...$params, 'preview']);

Header size limits

Cache providers cap the tag header — Fastly's Surrogate-Key allows 1024 bytes per key and 16384 bytes total, and silently drops the offending key and every key after it once a limit is reached, which would leave content stale. Cloudflare's Cache-Tag is likewise capped at 16 KB in total and allows only printable ASCII. To stay safe (for both front-end pages and REST responses):

  • Tags that aren't valid single header tokens — anything but printable ASCII, a space or comma (the two separators), or longer than the store column (191 bytes) — are dropped.
  • When the combined header would exceed the byte budget, the per-object post:/term: tags are collapsed to their coarse archive:{type}:any / taxonomy:{tax}:any form, which is purged on any change to that post type or taxonomy. This over-purges rather than dropping tags.
// Tag header byte budget before collapsing to coarse tags (default 16384,
// Fastly's Surrogate-Key total). Tune it for a provider with a different limit.
add_filter('cachetags/max-header-bytes', fn () => 8192);

(The single-tag length cap — 191, the varchar(191) store column — and the header-token validation pattern are fixed, not filterable: they're tied to the schema and to header safety.)

Front-end tagging

With the Core action enabled, rendered pages are tagged automatically from the template (single/page, taxonomy, author, post-type/date/search archives, attachments) and from core blocks (queries, terms, authors, comments, calendar/archives, site title/tagline/logo, etc.). Classic-theme wp_nav_menu() output is tagged with its menu:{id} so menu edits purge the pages showing it. A menu rendered by location is also tagged menu-location:{location}, also while the location is empty; tag a theme's own location renders (e.g. Navi) with CoreTags::navigation($location), which returns both. CoreTags::menu() returns no tags for a menu that doesn't exist (a location pointing at a deleted menu), since nothing renders.

A menu item takes its label and URL from the post or term it links to, so menu:{id} is also cleared for every menu linking to a post whose title, slug, parent, status or (with a date permalink) date changes, including trash and delete, or whose category changes with a %category% permalink (%product_cat% in WooCommerce's product base); and for every menu linking to a term whose name, slug or parent changes, or that is deleted. Other saves leave the menu alone. Deleting a menu clears its own tag. Assigning a location another menu, its first menu or none (the nav_menu_locations theme mod, and with Polylang each language's location in its polylang option) clears menu-location:{location}. With Polylang the tag is qualified with the page's language (menu-location:primary:fi), so reassigning one language's menu purges only that language's pages.

Known limits (flush manually)

These change what pages show without the hooks the purges listen to, so flush (wp cachetags clear page, or flush) after them:

  • Child pages under a renamed or moved parent. A child's URL changes with its parent's slug or parent, but only the parent's own tags are cleared: menus and Polylang language switchers linking to the child stay stale.
  • Polylang synchronisation. Polylang writes synchronised post and term parents with direct SQL, so neither the menu nor the translation purges see the change.
  • Polylang language slug changes. Every URL in that language changes.
  • Polylang default-language changes. Polylang Pro renames translated template parts (footer___sv → footer) with direct SQL, and default-language URLs change.
  • Polylang's bulk "set language" (set_translation_in_mass) writes languages and translation groups in bulk, without the group term edits the translation purge listens to.
  • Renamed terms in a permalink. With %category% (or %product_cat%) in the permalink, renaming the term changes every post URL under it; menus and switchers linking to those posts aren't cleared. Custom post type rewrite tags aren't detected at all.
  • WXR imports (Tools → Import) write posts, terms and menus in bulk, partly without the save hooks.
  • The navigation block's overlay template part isn't tagged.

Site-identity blocks (core/site-title, core/site-tagline, core/site-logo) are tagged with an option:{name} tag and purged when that option changes. Adjust which options are tracked with the cachetags/options filter:

add_filter('cachetags/options', fn (array $options) => [...$options, 'my_option']);

Options not bound to a specific block are usually better handled with a full cache flush than by tagging every page that might render them.

Zero-config auto-tagging

For themes that render content through custom WP_Query loops (related posts, curated lists) rather than the blocks Core understands, enable the opt-in AutoTag action to tag every queried post and fetched term automatically:

use Genero\Sage\CacheTags\Actions\AutoTag;
use Genero\Sage\CacheTags\Actions\Core;

return [
    'action' => [
        Core::class,
        AutoTag::class,
    ],
];

It hooks posts_pre_query (tagging each returned post, plus an archive:{type} for collection queries) and get_the_terms (tagging each term). posts_pre_query is used rather than the_posts because get_posts()/get_children()/ get_pages() force suppress_filters=true and so never fire the_posts — the pre-query hook fires for every WP_Query regardless, so a plain foreach (get_posts(...) as $post) loop is covered too. Raw $wpdb queries are not (no query object to observe) — tag those explicitly. Page archives are excluded by default — adjust with the cachetags/autotag-excluded-archive-types filter. The header-size collapse keeps the broader tag set bounded.

Cacheability

Some responses must never be stored in a shared cache. Util::isCacheableRequest() returns false for previews and any request showing the admin bar (per-user chrome baked into the HTML), and — by default — for logged-in users. When a request is not cacheable the plugin skips tagging it and defines DONOTCACHEPAGE so page caches (WP Super Cache, Batcache, theme cache-control providers) don't store it; edge caches should consult Util::isCacheableRequest() from the theme/VCL since their TTL header is sent earlier.

Integrations hook the single cachetags/cacheable filter. Responses are vetoed at the default priority; opt-ins that re-enable logged-in users run earlier (priority <10) so the vetoes always win:

  • WooCommerce — non-cacheable on cart/checkout/account, add-to-cart/ wc-ajax, an embedded login/register/lost-password form, and any page with a cart/checkout block or shortcode (these render per-user cart state).

  • Gravityform — a form prepopulated from the query string is non-cacheable (its prefilled values are per-visitor, often PII).

  • CacheCustomers (opt-in) — serve cached pages to logged-in customers/ subscribers, who see identical catalog pages and whose admin bar WooCommerce hides. Enable only when the theme renders no per-user markup server-side and the edge stops bypassing their login cookie; cart/checkout/account still bail. Roll your own with an early-priority raise:

    add_filter('cachetags/cacheable', fn ($c) => current_user_can('edit_posts') ? $c : true, 5);

Nonces in cached pages

A page cached for hours can ship a stale nonce. WordPress nonces are valid for 12–24h; once one ages out, the action it guards (a form submit, an AJAX "load more", an add-to-cart) starts failing for everyone served the cached page.

Two ways to handle a page that bakes a nonce into its HTML:

  1. Tag it nonce. The page is then purged every 12 hours, before any embedded nonce can expire. The Nonce action runs that cron and is enabled by default, so you only need to add the tag where the nonce renders (the Gravityform action already does this for file-upload forms):

    // e.g. a product page that prints a WooCommerce Store API nonce for add-to-cart
    add_action('wp_footer', function () {
        if (function_exists('is_product') && is_product()) {
            \Genero\Sage\CacheTags\CacheTags::getInstance()?->add(['nonce']);
        }
    });

    Remove Nonce::class from the action config to opt out of the cron.

    The soft invalidators (CloudflareSoftCacheInvalidator, FastlySoftCacheInvalidator) purge nonce hard: a soft purge would keep serving the old page, and its expired nonce, to the first visitor after it, which on a quiet page can be days later. Tag your own pages that must never be served stale the same way, or opt out:

    add_filter('cachetags/hard-purge-tags', fn (array $tags) => [...$tags, 'gform:5']);
    add_filter('cachetags/hard-purge-tags', '__return_empty_array'); // soft-purge everything

    A purge that includes one of these tags goes hard as a whole. One that is rate-limited and deferred to cron is retried soft.

  2. Mark it non-cacheable when the page also shows genuinely real-time data (e.g. live availability), where a 12h refresh isn't enough:

    add_filter('cachetags/cacheable', fn ($c) => is_page('booking') ? false : $c);

Note that modern WooCommerce (10.7+) refetches the Store API nonce client-side before a write, so the sitewide Store API nonce is no longer a staleness risk on its own — only nonces that are actually used as rendered need this treatment.

Gravity Forms state token

Gravity Forms 3 embeds a timestamped state token in every form, valid for 48 hours. Served from a cache older than that, the honeypot and state-validated fields (choices, consent, name, address, …) reject every submission; with the honeypot set to abort, silently, behind a confirmation message.

Purging every form page isn't the fix, since a form in the footer is on every page. Only the timestamp ages, so instead raise the lifespan past your edge cache's max TTL (a cached page hands every visitor the same token anyway):

// Edge caches pages for up to 7 days.
add_filter('gform_state_lifespan', fn () => 8 * DAY_IN_SECONDS);

Traits for use with roots/sage

Composers

namespace App\View\Composers;

use Genero\Sage\CacheTags\Concerns\ComposerCacheTags;
use Genero\Sage\CacheTags\Tags\CoreTags;
use Roots\Acorn\View\Composer;
use Illuminate\View\View;

class ContentSingle extends Composer
{
    use ComposerCacheTags;

    protected static $views = [
        'partials.content-single',
    ];

    /**
     * @return array
     */
    public function with()
    {
        $post = get_post();

        return [
            'post' => $post,
            'date' => $this->date($post),
            'authors' => $this->authors($post),
            'excerpt' => $this->excerpt($post),
            'related' => $this->related($post),
            'categories' => $this->categories($post),
        ];
    }

    public function cacheTags(View $view): array
    {
        return [
            ...CoreTags::posts($view->post),
            ...CoreTags::terms($view->categories),
            ...CoreTags::query($this->related())
        ];
    }
}

ACF Blocks

namespace App\Blocks;

use Genero\Sage\CacheTags\Tags\CoreTags;
use Genero\Sage\CacheTags\Concerns\BlockCacheTags;

class ArticleList extends Block
{
    use BlockCacheTags;

    public $name = 'Article List';
    public $slug = 'article-list';

    public function cacheTags(): array
    {
        $query = $this->buildQuery();

        return [
            ...CoreTags::archive('post'),
            ...CoreTags::query($query),
        ];
    }
}

Integrations

WooCommerce, Polylang & Gravity Forms (auto-enabled)

When WooCommerce, Polylang or Gravity Forms is active, its action is enabled automatically — you don't need to list it in action:

  • WooCommerce keeps cart/checkout/account out of the shared cache and purges a product (plus its archives where listings can change) on price/stock/status changes.
  • Polylang makes archive tags language-specific (archive:post:fi) so a change in one language only purges that language's listings, and clears the right language archives on publish/unpublish/delete. Language switchers link to a page's translations, so a post or term page carries one translations:{group} tag for its translation group, cleared only when what a switcher shows changes: a translation linked or unlinked, or a member's URL changing (slug, parent, status, and the date with a date-based permalink structure; a term's slug or parent). A content or title edit of one translation doesn't purge the others.
  • Gravity Forms keeps prepopulated forms out of the shared cache and purges a form's pages when it changes. It tags file-upload form pages nonce; the always-on Nonce action (not Gravity Forms) purges those before the nonce expires. GF 3's state token on every form expires separately and is left to the project; see Gravity Forms state token.

The WooCommerce action tags every product loaded while rendering, so a page showing a product is purged through its post:{id}. archive:product is only cleared when a change can alter which products a listing selects or their order: publish, unpublish, stock status, terms, or a save changing a prop like price or name (see WooCommerce::NON_LISTING_META_PROPS).

To manage the action list entirely yourself, turn detection off:

// config/cachetags.php
'auto-detect-actions' => false,
// or on the standalone bootstrap
(new Bootstrap)->autoDetectActions(false)->/* … */->bootstrap();

Flushing all pages, or a whole language

Every cacheable page and REST response carries a base page tag, so a single purge clears all WordPress-served pages at once — static assets (images/CSS/JS), which never carry it, stay cached:

wp cachetags clear page

Rename it or turn it off with 'base-tag' => null (config) / ->baseTag(null) (bootstrap).

Site Editor content

Pages are tagged with the block template they resolve to and the template parts they render, keyed by theme and slug: template:{theme}//{slug} and template-part:{theme}//{slug}. Both the core/template-part block and PHP block_template_part('footer') are covered. The key always uses the active theme, also for a plugin's own template (WooCommerce resolves woocommerce/woocommerce//single-product), since its customisation is saved under the active theme. Because the key isn't a post id, the theme file, its first customisation and "Clear customizations" (which force-deletes the post) all purge the same pages. Publishing, updating, trashing or deleting a wp_template / wp_template_part that is or was published, draft or auto-draft clears its key (block_template_part() renders drafts too). A theme action that purged on these saves (or flushed the whole cache) can be removed.

With Polylang, a template part's key is qualified with the page's language (template-part:{theme}//footer:sv). Polylang Pro stores a translated part as its own post (footer___sv) and falls back to the default language's part, so saving footer___sv purges only Swedish pages, saving footer purges the default language and every language without its own translation, and adding or removing a translation purges that language.

The inlined global styles and the Customizer's Additional CSS render on every page, so saving wp_global_styles (except the empty stub the block editor creates for a theme without user styles) or custom_css clears the base tag. So does adding or removing a template in the hierarchy that no theme file backs and no plugin registers (register_block_template(); WooCommerce's category, tag and brand templates aren't registered), since that changes which template pages resolve to; a wp-custom-template-* template doesn't, as only the posts assigned to it render it. With the base tag turned off, nothing purges on those saves.

When Polylang is active, every page is also tagged with its language, so you can clear all content in one language:

wp cachetags clear lang:fi

The Site action

On multisite where one edge (e.g. a single Fastly service) fronts the whole network, enable the Site action. It prefixes every tag with the site id (site:5:post:123) so a purge on one site never clears same-id content on another, and tags each page with site:{id} for a per-site flush-all (wp cachetags clear site:5). On a single site you don't need it — the base page tag above already gives flush-all without the per-tag prefixing.

Note the Site prefix also applies to the base tag, so with Site active the flush-all key is per-site site:5:page rather than the bare page.

Multisite tables

Each site has its own cache_tags table, provisioned on activation and when a new subsite is created. Run wp cachetags database to (re)scaffold every site — useful after activating on a large network where the activation request can't finish provisioning all of them.

CLI

With Acorn:

# Flush the entire cache
wp acorn cachetags:flush

# …purging with soft invalidators too, so nothing stale is served
wp acorn cachetags:flush --hard

# Clear specific tags
wp acorn cachetags:clear post:1 term:5

# Scaffold database table (all sites on multisite)
wp acorn cachetags:database

# Migrate the table to the latest schema (drop + recreate + flush the cache)
wp acorn cachetags:database --rebuild

# Inspect the store: row/tag/url counts and the widest-fan-out tags
wp acorn cachetags:status
# …or the tags a given URL is stored under (an argument: WP-CLI takes --url
# as its own global flag)
wp acorn cachetags:status https://example.com/article/

# Garbage-collect store rows not re-rendered within the age (see note below)
wp acorn cachetags:prune --older-than=30d

# Request the pages purges queued (see Warming the cache)
wp acorn cachetags:warm

Standalone:

# Flush the entire cache
wp cachetags flush

# …purging with soft invalidators too, so nothing stale is served
wp cachetags flush --hard

# Clear specific tags
wp cachetags clear post:1 term:5

# Scaffold database table (all sites on multisite)
wp cachetags database

# Migrate the table to the latest schema (drop + recreate + flush the cache)
wp cachetags database --rebuild

# Inspect the store
wp cachetags status
wp cachetags status https://example.com/article/
# …on a multisite subsite (WP-CLI's --url picks the site)
wp --url=https://sub.example.com cachetags status https://sub.example.com/article/

# Garbage-collect store rows not re-rendered within the age (see note below)
wp cachetags prune --older-than=30d

# Request the pages purges queued (see Warming the cache)
wp cachetags warm

status answers "what's bloating the store / why was this purged so widely" — a tag with a high URL count purges that many pages on a single change. It requires a store that supports inspection (the default WordpressDbStore does).

prune garbage-collects store rows whose URL hasn't been rendered within the given age (12h/30d/4w) — query-string, bot and campaign-link variants that otherwise accumulate forever, especially on query-bypass edges. A row's age is last seen (refreshed on each render, at most once a day to avoid write churn), so actively-served pages are never pruned.

This runs daily by default (the prune-older-than config, default 30d) — the manual command above just forces a run. The age must exceed your edge cache's max TTL: pruning a URL still cached at the edge leaves an object you can no longer purge by tag (on Kinsta/Fastly the max TTL is ~30d, so raise it if your edge holds objects that long). Disable GC with 'prune-older-than' => null. Only a prunable store (the default WordpressDbStore) is affected — TransientStore no-ops.

The store is a rebuildable cache, so --rebuild migrates an existing (even million-row) table to the latest schema by dropping and recreating it — avoiding a slow, locking ALTER — and flushes the edge so nothing is left stale while the store refills. Run it in a low-traffic window; the cold cache warms as pages re-render.

Warming the cache

A purged page is rendered again by whoever asks for it next: a visitor, or a crawler walking every page, which can take a site down when the cache is cold. The warmer re-requests purged pages from the server itself first, at a pace a single visitor would cause.

List WarmInvalidator after the invalidator that purges, and run the command from the server's crontab:

'invalidator' => [
    KinstaGroupCacheInvalidator::class,
    \Genero\Sage\CacheTags\Invalidators\WarmInvalidator::class,
],
* * * * * cd /path/to/site/web && ../vendor/bin/wp cachetags warm --quiet
# Weekly, before the cache expires: every page the store holds
0 4 * * 0 cd /path/to/site/web && ../vendor/bin/wp cachetags warm --all --seconds=3000 --quiet
  • A purge queues its URLs; a flush queues every URL the store holds. Each waits 30 seconds, so the purge has reached the cache before it's requested again.
  • Each run requests queued pages one at a time (--pause, default 0.2s) for --seconds (default 50) as an anonymous visitor: no cookies, no login.
  • A run stops when the site answers 429 or 503, so warming never competes with real traffic: a rate limiter or host in front of PHP decides when the site is too busy. The rest waits for the next run.
  • Only plain pages are warmed. URLs with a query string (search, facets, campaign links) are skipped, and so are REST, admin and login URLs. Skip more with path patterns in the config's warm-skip, e.g. '#^/search/#' or '#/page/\d{2,}/#', or the cachetags/warm/skip filter ($skip, $url).
  • cachetags/warm/request-headers sets the headers each request sends, e.g. for something in front of PHP to recognise the warmer.

The queue lives in an option, capped at 20,000 URLs. It's best effort: a URL lost to two purges landing at once is simply cached by its next visitor.

API

Accessing CacheTags instance

With Acorn:

use Genero\Sage\CacheTags\CacheTags;

// Get instance from container
$cacheTags = app(CacheTags::class);

Standalone:

use Genero\Sage\CacheTags\CacheTags;

// Get the singleton instance
$cacheTags = CacheTags::getInstance();

Building tags with Tag

Tags are Tag value objects — fluent to build, serialized to their string form (post:5, archive:post:any, site:5:term:9) only at the edge (header, store, purge). add() and clear() accept Tags, plain strings, and nested arrays interchangeably, so you rarely touch Tag directly — but it's there when you want type-safety or context.

use Genero\Sage\CacheTags\Tag;

Tag::post(5);                    // post:5
Tag::archive('product');         // archive:product
Tag::archive('product')->any();  // archive:product:any  (any product changing)
Tag::term(9)->full();            // term:9:full
Tag::option('blogname');         // option:blogname
Tag::of('my-type', $id);         // an arbitrary custom type

Context is two general, composable operations — scope() to namespace a tag and qualify() for a variant — so new dimensions (a multisite network, a tenant) need no new API:

Tag::post(5)->scope('site', 5);                       // site:5:post:5
Tag::post(5)->scope('network', 2)->scope('site', 5);  // network:2:site:5:post:5
Tag::archive('post')->qualify($lang);                 // archive:post:fi

The builder classes (CoreTags, WooCommerceTags, SiteTags, PolylangTags, GravityformTags) return Tag[]; pass them — and any plain strings — straight to add()/clear(). Both take tags as individual arguments or arrays, nested freely:

$cacheTags->add(Tag::nonce());                 // a single tag
$cacheTags->add('post:5', Tag::term(9));       // several arguments
$cacheTags->add([
    Tag::archive('product'),
    ...CoreTags::posts($ids),                  // CoreTags returns Tag[]
    'my:custom:tag',                           // plain strings still work
]);

Create a custom tag

The nicest way is to look at the code of this repo and create a custom Action, but the logic is really nothing more than:

With Acorn:

use Genero\Sage\CacheTags\CacheTags;
use Genero\Sage\CacheTags\Tag;

// Tag content (a bare string, or Tag::of('custom-tag') / Tag::of('thing', $id))
app(CacheTags::class)->add(['custom-tag']);

// Clear it whenever you want
\add_action('custom/update', fn() => app(CacheTags::class)->clear(['custom-tag']));

Standalone:

use Genero\Sage\CacheTags\CacheTags;

// Tag content
CacheTags::getInstance()?->add(['custom-tag']);

// Clear it whenever you want
\add_action('custom/update', fn() => CacheTags::getInstance()?->clear(['custom-tag']));