Clear the cache on every path that publishes, not just the one you click
One of my side projects is a WordPress site where most new articles are published by a script, not by a person clicking a button. The script creates a post through the REST API, fills it in, and then flips its status to published with one more API call. That part worked fine. New articles showed up on the site every day.
What did not show up was any of them in the sitemap. The sitemap files were frozen on a snapshot from about six weeks earlier. Every article published since then was missing, and search engines were not picking them up. Nothing errored. The sitemap returned a 200 with valid XML. It was just old.
Why it froze
The SEO plugin that builds the sitemaps caches them, which is reasonable, because generating a sitemap for thousands of posts on every request is slow. It is supposed to clear that cache when a post is published. In practice, that clearing was reliable when someone saved a post in the admin screen and not reliable on the path my script used.
I had hit a version of this before and fixed it with a one-time reset: flush the whole sitemap cache once and let it rebuild. It did rebuild, the dates moved forward, and then they froze again a day later. The reset treated the symptom. The real problem was that the publish path I actually used every day never told the cache anything had changed.
There was a second layer, too. A full-page cache sat in front of the site, and it had no rule saying sitemap URLs should be skipped. So even a freshly rebuilt sitemap could be served stale from the page cache.
List every way content changes
The fix started with a list, not code. For this one post type, content can change state through:
- Saving the post in the admin editor.
- Creating or updating it through the REST API, which is what the script does.
- A status transition, for example draft to published, or published back to draft.
Each of those fires a different hook. Some fire together on the same request, some do not. If cache invalidation only hangs off one of them, any content that arrives through another path leaves the cache stale. The question to ask is not “does publishing clear the cache?” but “does every way of publishing clear the cache?”
Unpublishing matters as much as publishing. A post that gets pulled should drop out of the sitemap too, or you keep advertising a URL that no longer exists.
One function, called from every hook
I put the actual work in one function and had every hook call it. The function decides whether the change matters, makes sure it only runs once per post per request, and then clears the sitemap types that include that post:
function invalidate_sitemaps_for_story($post_id, $post = null, $force = false) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (wp_is_post_revision($post_id)) {
return;
}
$post = $post ?: get_post($post_id);
if (!$post || $post->post_type !== 'story') {
return;
}
if (!$force && $post->post_status !== 'publish') {
return;
}
static $done = array();
if (isset($done[$post_id])) {
return;
}
$done[$post_id] = true;
clear_sitemap_cache(array('story', 'news', 'index'));
}
add_action('save_post_story', function ($id, $post) {
invalidate_sitemaps_for_story($id, $post);
}, 20, 2);
add_action('rest_after_insert_story', function ($post) {
invalidate_sitemaps_for_story($post->ID, $post);
}, 20, 1);
add_action('transition_post_status', function ($new, $old, $post) {
if ($new !== $old && ($new === 'publish' || $old === 'publish')) {
invalidate_sitemaps_for_story($post->ID, $post, true);
}
}, 20, 3);
A few details in there are doing real work:
- The early returns skip autosaves and revisions, which fire save hooks constantly and are never what a reader sees.
- The static
$donearray stops one publish from clearing the cache three times when the save, REST, and transition hooks all fire on the same request. - The
$forceflag lets the status transition clear the cache even when the new status is not published. That is how unpublishing gets covered. - Clearing the index too, not just the post type’s own sitemap, because the index carries the last-modified dates search engines use to decide what to recrawl.
Keep the page cache out of it
The second fix was smaller. On sitemap requests, the theme now tells the page cache not to store the response, and the sitemap URL patterns are added to the page cache’s list of URLs it should never cache. The sitemap plugin already has its own cache. Two caches stacked on the same response just means two places to go stale.
Make the one-time reset safe
I still wanted one clean flush after deploying, to throw away the frozen snapshot. The earlier reset was guarded by an option flag, so it had already run and would never run again. I bumped the flag name to a new version, which makes the reset run once more on the next request.
Since many requests can arrive at the same moment after a deploy, the reset claims the flag with
add_option, which only succeeds for one caller because the option name is unique. Whoever wins
does the flush. Everyone else skips it. Checking with get_option and then setting it later
would leave a window where several requests all decide they are first.
Tradeoffs
Clearing the cache on every publish means the next sitemap request pays the cost of regenerating it. For a site that publishes a handful of articles a day, that is nothing. If you publish thousands of items an hour, you would want to batch or debounce the invalidation instead of firing it per post.
Hooking several events also means you are relying on the dedupe to keep it cheap. Without it, one publish can do triple the work, and that is easy to miss because nothing breaks. It is just slower.
And the versioned reset is a blunt tool. It is fine for a one-off cleanup, but if you find yourself bumping it again, that is a sign some write path is still not invalidating.
Test the parts you can
Most of this lives inside WordPress hooks, which are awkward to test. I kept the decisions in small pure functions instead: which request paths count as sitemaps, and which sitemap types a given post should clear. Those run from a plain command-line test with no WordPress loaded, and the file skips registering hooks when WordPress functions are not present.
The lesson I keep relearning is that a cache is only as fresh as the least-watched path that writes to it. When you add a new way to publish, whether that is a script, an import, or an API client, go find every cache downstream of that content and check that it hears about the change.