Fixing category count
-
22-04-2021 - |
Frage
Somehow my post counts are incorrect due to inserting rows via php. I have the following code to update the count, is it correct?
global $wpdb;
$result = mysql_query("SELECT term_id,term_taxonomy_id FROM $wpdb->term_taxonomy where taxonomy = 'category'");
while ($row = mysql_fetch_array($result)) {
$term_taxonomy_id = $row['term_taxonomy_id'];
$countresult = mysql_query("SELECT object_id FROM $wpdb->term_relationships WHERE object_id IN (SELECT ID FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish') AND term_taxonomy_id = '$term_taxonomy_id'");
$count = mysql_num_rows($countresult);
mysql_query("UPDATE $wpdb->term_taxonomy SET count = '$count' WHERE term_taxonomy_id = '$term_taxonomy_id'");
}
Lösung
If you just want to update the counts of posts in each term, wp_update_term_count_now( $terms, $taxonomy )
should do it... just pass the terms affected as an array and run it once for each taxonomy you have.
You can also call wp_defer_term_counting( true )
before inserting new rows, and then after adding your posts, catch up on the counts by calling wp_defer_term_counting( false )
.
Andere Tipps
There's a sql script written by someone else that does the job - updates counts for product categories in woocommerce or any other category counts.
Only takes a few seconds to run as well:
Example for the answer of goldenapples:
$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);
In my opinion the best way to do this is by using WP-CLI. There's a command for that:
$ wp term recount category
Find the documentation here: https://developer.wordpress.org/cli/commands/term/recount/