query-id-cache: remember post IDs for slow WP_Query lists

A WordPress plugin that remembers the post IDs and row counts of slow secondary queries for a few minutes and hands them back to anonymous requests, with invalidation on every change that could alter a list.

query-id-cache is a WordPress plugin for sites whose pages run many secondary WP_Query calls to fill card lists and widgets. It remembers which post IDs each slow query returned, and how many rows it counted, and serves that to the next anonymous request. Posts still load fresh by primary key. The code is at https://github.com/IndianOpinion/query-id-cache, under the MIT licence. Version v0.1.0 was released on 14 November 2026.

The problem

Some pages run dozens of secondary queries: “latest in category X”, “most viewed”, “most commented”. On a site with no persistent object cache, nothing keeps their results between requests, so every page-cache miss pays for every query again.

The expensive part is almost never loading the posts. It is finding which IDs belong in each list: ordering every published post by a meta value or comment count, or counting a large category for pagination. The posts themselves load quickly by primary key. A full-page cache hides this from most visitors, but every miss (expiry, a purge after a publish, a new query string, a crawler on a cold edge) pays the full cost. On a site that publishes often, the page cache is purged often.

What it does

  • Stores the ordered ID list and found-rows count of each eligible secondary query, for 300 seconds by default.
  • Serves them from posts_pre_query on a hit, sets found_posts and max_num_pages, and primes the post cache in one query.
  • Lets the site declare which queries are eligible, as named signatures registered with register_signature(). One signature, front-page, is registered by default.
  • Drops entries on publish, unpublish, delete, term changes and sticky changes that could alter a list.
  • Offers wp query-id-cache status, list and flush, an optional debug header, and hit and miss actions.

How it works

A request is eligible only if it is an anonymous front-end request: not admin, AJAX, cron, REST, WP-CLI, XML-RPC, a preview, or signed in. A query is eligible if it is a secondary query that matches a signature on its parsed variables. The key is a SHA-256 hash of the final SQL, the fields mode, the signature, the blog ID and a data-format version.

  • On a hit, the IDs come back at posts_pre_query priority 20. Any ID that is no longer published is dropped using only what is in memory, and the entry is deleted if one was.
  • On a miss, the real query runs. The raw IDs are taken at posts_results (earliest priority) and recorded with the final count at the_posts (latest priority). Recording at the end would apply result filters twice on a hit.
  • New entries are buffered and written once, at shutdown. If an invalidation ran during the request, the new entries are discarded instead.

Lists have a freshness class. fresh lists (ordered by date, modified date or ID) are dropped by any publish change in their scope. ttl lists (meta value, comment count, title) live out their time to live, so popularity lists may lag by design. Term scope is read from the parsed tax query and resolved the way WordPress does, including child terms.

Storage is one transient blob without a persistent object cache, which costs one database read per request. With Redis or Memcached each entry is its own item under a generation number, and any invalidation bumps the generation. Registering a signature for section pages looks like this:

use function IndianOpinion\QueryIdCache\register_signature;

add_action('init', static function (): void {
    register_signature('sections', ['context' => 'archive']);
}, 20);

new WP_Query(['posts_per_page' => 5, 'query_id_cache' => false]); // never cache this one

Guard rails

  • Never cached: the main query, suppress_filters queries, random order, any author constraint, any status other than exactly publish, searches, post__in lists, post type any, and anything inside switch_to_blog().
  • Entries hold IDs only. Content edits need no invalidation, and previews and signed-in users are never served.
  • If a later component answers a query after this plugin’s priority, the plugin steps aside and does not record that answer as a database result.
  • Every filter and action callback catches Throwable, logs once per kind per request and returns its input. A throwing match callback disables only that signature for the request. If an invalidation handler throws, the whole store is flushed, because a missed invalidation could leave a stale “latest” list.
  • Caps on entries (300) and bytes (524,288) apply. QUERY_ID_CACHE_DISABLE registers no hooks at all.
  • status flags a signature as “keys never repeat” when it has stored 50 or more entries and never rewritten one. That usually means a relative date in the SQL.

What review changed

  • Term scope never worked against real WordPress. WP_Tax_Query keeps clauses as written, but the code only accepted already-transformed clauses. Every term-filtered list read everything, and a publish into a child category did not drop the parent’s “latest” list. Each clause is now resolved with the same steps core uses, and created_term invalidation was added.
  • A component hooked after priority 20 could answer a pending query, and its answer was recorded as a database result. A check at PHP_INT_MAX now clears the pending state.
  • With a custom posts_fields, rows without IDs were reduced to a short list and cached. Such a query is now left unrecorded.
  • is_user_logged_in() could make core settle the current user too early when a query ran before init. It is now asked only after the main query has run.

Limits and what is next

  • Anonymous requests only. Signed-in users always get the real queries.
  • With an object cache, an invalidation that matches orphans every entry, not just the matching ones.
  • Popularity lists lag by up to their time to live.
  • A fields => ids query with no_found_rows that reuses its query object loses the first run’s recording. The page is still correct.
  • Open issue 3: the PRD’s case 9 was wrong about suppress_filters. WordPress runs posts_pre_query for such queries, so the plugin excludes them itself. The README says so, and notes that get_posts() suppresses filters by default. The issue asks for the PRD to be corrected.

Test status: this is v0.1.0. 182 PHPUnit tests (526 assertions) pass against a stub layer that reproduces core’s hook order around the short-circuit, with PHPStan level 8 and phpcs clean. It has not run on a real WordPress or a live site. CI has not yet run on GitHub. The speed-up on a live page is not measured by this repo.

Install

Requires PHP 8.1 or later and WordPress 6.4 or later, with no runtime dependencies.

The package is not on Packagist yet, so first add a Composer vcs repository entry for https://github.com/IndianOpinion/query-id-cache.

composer require indianopinion/query-id-cache

Without Composer, unpack a release into wp-content/plugins/query-id-cache/ and activate it. For a must-use install, copy examples/mu-plugin-loader.php into wp-content/mu-plugins/.

All 47 utilities · query-id-cache on GitHub

Search Trending
Loading

Signing-in 3 seconds...

Signing-up 3 seconds...

All fields are required.