_update_generic_term_count()
云策文档标注
概述
_update_generic_term_count() 是 WordPress 中用于更新术语计数的核心函数,作为 'link_category' 分类法的默认回调。它基于对象数量计算并更新术语计数,涉及数据库操作和钩子触发。
关键要点
- 函数用途:更新术语计数,基于 term_taxonomy_id 从 term_relationships 表统计关联对象数量。
- 参数:$terms(必需,术语分类ID数组)和 $taxonomy(必需,当前分类法对象)。
- 核心操作:循环处理每个术语,使用 wpdb 查询计数,触发 update_term_count、edit_term_taxonomy 和 edited_term_taxonomy 钩子,并更新 term_taxonomy 表。
- 钩子:包括 update_term_count(计数计算后、数据库更新前触发)、edit_term_taxonomy(关系更新前触发)和 edited_term_taxonomy(关系更新后触发)。
- 相关函数:涉及 wpdb::update()、do_action()、wpdb::get_var() 和 wpdb::prepare() 等。
- 版本历史:自 WordPress 3.3.0 引入。
代码示例
function _update_generic_term_count( $terms, $taxonomy ) {
global $wpdb;
foreach ( (array) $terms as $term ) {
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'update_term_count', $term, $taxonomy->name, $count );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
}
}
原文内容
Updates term count based on number of objects.
Description
Default callback for the ‘link_category’ taxonomy.
Parameters
$termsint[]required-
List of term taxonomy IDs.
$taxonomyWP_Taxonomyrequired-
Current taxonomy object of terms.
Source
function _update_generic_term_count( $terms, $taxonomy ) {
global $wpdb;
foreach ( (array) $terms as $term ) {
$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'update_term_count', $term, $taxonomy->name, $count );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'edit_term_taxonomy', $term, $taxonomy->name );
$wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) );
/** This action is documented in wp-includes/taxonomy.php */
do_action( 'edited_term_taxonomy', $term, $taxonomy->name );
}
}
Hooks
- do_action( ‘edited_term_taxonomy’, int $tt_id, string $taxonomy, array $args )
-
Fires immediately after a term-taxonomy relationship is updated.
- do_action( ‘edit_term_taxonomy’, int $tt_id, string $taxonomy, array $args )
-
Fires immediate before a term-taxonomy relationship is updated.
- do_action( ‘update_term_count’, int $tt_id, string $taxonomy_name, int $count )
-
Fires when a term count is calculated, before it is updated in the database.
Changelog
| Version | Description |
|---|---|
| 3.3.0 | Introduced. |