Fixing category count

时间:2011-03-02 作者:Innate

不知何故,由于通过php插入行,我的帖子计数不正确。我有以下代码来更新计数,是否正确?

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\'");
        }

4 个回复
最合适的回答,由SO网友:goldenapples 整理而成

如果你只想更新每个学期的职位数量,wp_update_term_count_now( $terms, $taxonomy ) 应该这样做。。。只需将受影响的术语作为一个数组传递,并为您拥有的每个分类法运行一次。

您也可以致电wp_defer_term_counting( true ) 在插入新行之前,然后在添加帖子之后,通过调用wp_defer_term_counting( false ).

SO网友:Dave Hilditch

有一个由其他人编写的sql脚本可以完成这项工作—更新woocommerce中产品类别的计数或任何其他类别的计数。

只需几秒钟即可运行:

https://stackoverflow.com/questions/18669256/how-to-update-wordpress-taxonomiescategories-tags-count-field-after-bulk-impo

SO网友:Martin from WP-Stars.com

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);

SO网友:David Faber

在我看来,最好的方法是使用WP-CLI. 有一个命令:

$ wp term recount category

请在此处查找文档:https://developer.wordpress.org/cli/commands/term/recount/

结束