How to update WordPress taxonomies(categories/tags)' count field after bulk import/delete

This SQL helps:

UPDATE wp_term_taxonomy SET count = (
SELECT COUNT(*) FROM wp_term_relationships rel 
    LEFT JOIN wp_posts po ON (po.ID = rel.object_id) 
    WHERE 
        rel.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id 
        AND 
        wp_term_taxonomy.taxonomy NOT IN ('link_category')
        AND 
        po.post_status IN ('publish', 'future')
)

A more WordPress-compliant way would be using wp_update_term_count_now (https://developer.wordpress.org/reference/functions/get_terms/)

Example:

$update_taxonomy = 'my_taxonomy';
$get_terms_args = array(
        'taxonomy' => $update_taxonomy,
        'fields' => 'ids',
        'hide_empty' => false,
        );

$update_terms = get_terms($get_terms_args);
wp_update_term_count_now($update_terms, $update_taxonomy);

The answer by @kaorukobo works well. However, I needed a bit more customization to automatically update all terms for a CPT... specifically a WooCommerce product CPT with several custom taxonomies...

The following updated all the taxonomies for the product CPT.

UPDATE wp_term_taxonomy tt
    SET count =
    (SELECT count(p.ID) FROM  wp_term_relationships tr
    LEFT JOIN wp_posts p
    ON (p.ID = tr.object_id AND p.post_type = 'product' AND p.post_status = 'publish')
    WHERE tr.term_taxonomy_id = tt.term_taxonomy_id
)

Tags:

Wordpress