📝 WordPress: Fix Taxonomy Term Counts Drifting After a Bulk Import
WordPress keeps a cached count column on each row in wp_term_taxonomy rather than counting wp_term_relationships rows live on every page load, and that cached count is only recalculated by the normal save flow — the hooks that fire around wp_set_object_terms() during a single post save in the admin. A bulk importer that inserts post rows and term relationship rows directly via $wpdb, or through wp_insert_post() called with term assignment skipped for speed and term relationships added afterward in a separate raw query, never triggers that recount path at all, so every affected term’s displayed count on the category/tag archive pages, in widgets, and in the admin term list keeps showing whatever it was before the import — sometimes zero — no matter how many posts actually carry that term now.
🔎 The Problem
-- What the bulk importer actually ran (fast, but skips recount hooks): INSERT INTO wp_term_relationships (object_id, term_taxonomy_id) VALUES (4821, 17), (4822, 17), (4823, 17), /* ...1200 more rows... */; -- Reality after the import: SELECT COUNT(*) FROM wp_term_relationships WHERE term_taxonomy_id = 17; -- 1,203 -- What WordPress is still showing everywhere (archive pages, widgets, admin): SELECT count FROM wp_term_taxonomy WHERE term_taxonomy_id = 17; -- 3 <- stale cached value from before the import ever ran
✅ Fix: Force a Real Recount After Any Direct-SQL Import
- Call WordPress’s own
wp_update_term_count_now( $term_taxonomy_ids, $taxonomy )once, right after the import finishes, passing every affectedterm_taxonomy_id— it runs the exact recount query the normal save flow would have triggered, just all at once instead of per post. - For a very large import, batch that recount call in chunks of a few hundred term IDs per request instead of one call covering tens of thousands of terms, since the recount itself runs a
COUNT()query per term and a single giant batch can itself time out on a slow host. - Add a WP-CLI step to the import script —
wp term recount <taxonomy>covers every term in that taxonomy in one command and is the simplest fix when the importer doesn’t already track which specific term IDs it touched.
🚨 Why This Is Dangerous
- A category archive page or a “posts in this category” widget that silently under-reports how much content actually exists there looks to an editor like the import failed entirely, sending them hunting for missing posts that are really just sitting there uncounted, not unindexed.
WordPress’s term counts are a cache of a count, not the count itself — and nothing refreshes a cache that the code path updating it was never asked to touch.




