☰
WORDPRESS / PRACTICE

Deferring Term Counting in WordPress During Bulk Imports

Deferring Term Counting in WordPress During Bulk Imports

During a large import, WordPress may spend a significant amount of time not creating posts, but updating category and tag counts. The issue is especially noticeable when an importer calls wp_set_object_terms() many times for different posts.

After terms are assigned, WordPress normally updates the number of associated objects. This is barely noticeable for a few dozen posts, but across thousands of posts the same operation may be repeated many times. For a controlled batch import, you can temporarily defer counting and then restore accurate values with one final update.

Why Taxonomy Counts Slow Down Imports

WordPress stores categories and tags separately from posts, while the relationships between them are stored in the term_relationships table. When a post receives a term through wp_set_object_terms(), WordPress does more than add the relationship. It also runs internal logic to update terms, caches, and their counts.

If one post receives several categories and tags while the importer processes thousands of posts, the number of repeated operations quickly increases. SQL queries, cache invalidation, and hooks that run after relationship changes create additional overhead.

It is important to distinguish between creating relationships between posts and terms and counting the number of objects in each term. The first must happen during the import, while the second can often be safely performed after the batch is complete.

  • The problem is most noticeable when importing thousands or tens of thousands of posts.
  • Delays may occur even when the data itself is imported correctly.
  • Deferred counting does not cancel relationship creation; it only postpones count updates.

How wp_defer_term_counting() Works

The wp_defer_term_counting(true) function enables deferred term count updates. While this mode is active, WordPress does not recalculate object counts after every taxonomy change. Instead, the affected terms are collected for later processing.

Calling wp_defer_term_counting(false) disables the mode and starts the final processing of the deferred counts. This is why the function must be called after the import in every case, including when an error occurs during processing.

Use this mechanism only around a controlled operation. Do not enable it globally for the entire site or leave it active during normal WordPress operations.

  • true — temporarily defer counting;
  • false — finish deferred mode and update the counts;
  • the final call must be guaranteed with a try...finally construct.
wp_defer_term_counting(true);

try {
    // Create or update posts.
    // Assign categories and tags through wp_set_object_terms().
    // Perform other operations belonging to this import.
} finally {
    // Finish deferred counting.
    wp_defer_term_counting(false);
}

A Safe Importer Pattern

All code that creates or changes relationships between posts and categories or tags should run inside deferred mode. If you enable it after part of the import has already run, the first posts will still trigger normal recounts.

If the importer works in batches, you can enable deferred counting at the beginning of each batch and disable it in that batch's finally block. This lets you complete smaller portions of the work regularly without leaving the state unfinished across the entire long-running process.

Errors affecting individual posts should ideally be logged separately. The occurrence of an error must not prevent the final wp_defer_term_counting(false) call. If the import should continue after an error, implement that behavior deliberately in the batch-processing logic rather than by ignoring exceptions.

  • Enable the mode immediately before the batch operation begins.
  • Put the disabling call in finally, not only after a line that may fail.
  • Do not mix uncontrolled third-party operations into the same process if they may depend on current term counts.
  • After each batch, check the number of processed posts and importer errors.

What Not to Do When Optimizing

The most dangerous way to speed up an import is to insert rows directly into term_relationships with SQL, bypassing the WordPress API. This may bypass hooks, cache invalidation, input validation, and the logic that updates related tables.

Even if you recalculate counts separately after using direct SQL, this does not guarantee behavior fully equivalent to WordPress's standard process. Use wp_set_object_terms() or other appropriate API functions to assign terms, and defer only the counting itself.

You should also avoid manually changing the count value in the terms table as a replacement for a normal recount. The count depends on the rules of the specific taxonomy, including the object types and statuses considered by its counting callback.

  • Do not edit term_relationships directly without a clear need and a full understanding of the consequences.
  • Do not set count manually based on a simple number of rows in the relationship table.
  • Do not leave deferred mode enabled after the importer finishes.
  • Do not treat a cached value as proof that the database contains correct counts.

Checking the Result After the Import

After the import finishes, check more than just the number of posts created. Also verify their taxonomy relationships. Select several categories and tags with different numbers of associated posts and compare the data in the administration area, on archive pages, and in your own query results.

If the site uses caching, make sure that page and object caches are not displaying old values after the import. wp_defer_term_counting() handles deferred counting within WordPress, but server-level, plugin-level, or external infrastructure caching may have a separate lifecycle.

For a technical check, you can compare the number of posts of a given type associated with a term against its count. The query must use the same conditions as the specific taxonomy, including post type, statuses, and its counting callback. A simple comparison with all rows in term_relationships may produce an incorrect result.

  • Check the terms that received the most new relationships.
  • Review category and tag archives on the frontend.
  • Check the importer logs for missing or duplicate assignments.
  • After an emergency stop, run the verification and recount procedure provided by your importer or WP-CLI command separately.

Common Mistakes and Practical Recommendations

The most common mistake is to enable deferred mode and terminate the PHP process before finally can run. Forced termination, a fatal error, or a server failure may prevent the final call from executing. For this reason, run large imports in an environment with logging, controlled batches, and the ability to verify the results again.

Another mistake is assuming that deferred counting will solve every performance problem. If the importer repeatedly searches for terms for each post, creates duplicates, or runs unnecessary queries, most of the load will remain. Optimize term lookup, reuse term IDs, and batch size separately from counting.

For critical imports, first test the process on a copy of the database. Check not only speed, but also reruns, partially imported posts, duplicates, and the accuracy of counts after an interruption.

  • Store the IDs of terms that have already been found so you do not look them up repeatedly without need.
  • Split very large imports into batches with a clear progress log.
  • Design reruns so they do not create duplicate relationships or terms.
  • Create a backup before working with production data.

Frequently asked questions

Can wp_defer_term_counting() be used for a normal update of one post?

Technically, the function can also work in that scenario, but it usually provides little practical benefit. It is primarily intended for controlled batch operations where repeated recounts create significant overhead.

What happens if wp_defer_term_counting(false) is not called?

Counts may remain outdated, and WordPress may stay in deferred mode until the current request ends or the state changes. This is why the disabling call should be placed in finally. After an emergency termination, check and recount the terms separately.

Can wp_set_object_terms() be replaced with direct SQL to speed things up?

This is not recommended. Direct writes to term_relationships bypass WordPress hooks, cache invalidation, and related internal logic. It is safer to keep the standard relationship creation process and optimize deferred counting and the importer structure instead.

Are counts updated immediately after wp_defer_term_counting(false)?

This call ends deferred mode and processes the accumulated changes. The database values should then be current according to the rules of the specific taxonomy, although external page or object caches may require separate invalidation.

How can I verify the result after an unsuccessful import?

Compare the number of imported posts, the relationships for selected categories and tags, and their count values. Also check importer logs, caches, and the rerun behavior for a partially completed batch.

Conclusion

Deferred term counting can reduce the number of repeated operations during a bulk WordPress import without abandoning the standard API for assigning categories and tags. The core pattern is simple: enable wp_defer_term_counting(true), run a controlled batch, and reliably finish it with wp_defer_term_counting(false) in finally.

This optimization is safe only when combined with result verification, error logging, and avoiding direct SQL changes to relationship tables. If the import stops unexpectedly, check counts and caches separately before the site begins displaying the data to users.

← All WordPress materials