跳转到主要内容

术语分割 (WordPress 4.2)

此信息出于历史目的而放在这里。如果您对 2015 年之前的术语如何运作不感兴趣,您可以跳过本节。

WordPress 4.2 之前的版本

具有相同 slug 的不同分类法中的术语共享一个术语 ID。例如,带有“新闻”标签的标签和类别具有相同的术语 ID。

WordPress 4.2+

从 4.2 开始,当这些共享术语之一更新时,它将被拆分:更新的术语将被分配一个新的术语 ID。

这对你来说意味着什么?

在绝大多数情况下,此更新是无缝且顺利的。但是,一些将术语 ID 存储在选项、帖子元、用户元或其他位置的插件和主题可能会受到影响。

处理分裂

WordPress 4.2 包含两种不同的工具来帮助插件和主题的作者进行过渡。

钩子split_shared_term_

当为共享术语分配新术语 ID 时,split_shared_term会触发新操作。

以下是插件和主题作者如何利用此挂钩来确保更新存储的术语 ID 的一些示例。

存储在选项中的术语 ID

假设您的插件存储一个名为的选项featured_tags,其中包含一组术语 ID ( [4, 6, 10]),用作主页精选帖子部分的查询参数。

在此示例中,您将挂钩split_shared_term操作,检查更新的术语 ID 是否在数组中,并在必要时进行更新。


/**
 * Update featured_tags option when a shared term gets split.
 *
 * @param int    $term_id          ID of the formerly shared term.
 * @param int    $new_term_id      ID of the new term created for the $term_taxonomy_id.
 * @param int    $term_taxonomy_id ID for the term_taxonomy row affected by the split.
 * @param string $taxonomy         Taxonomy for the split term.
 */
function wporg_featured_tags_split( int $term_id, int $new_term_id, int $term_taxonomy_id, string $taxonomy ): void {
	// we only care about tags, so we'll first verify that the taxonomy is post_tag.
	if ( 'post_tag' === $taxonomy ) {

		// get the currently featured tags.
		$featured_tags = get_option( 'featured_tags' );

		// if the updated term is in the array, note the array key.
		$found_term = array_search( $term_id, $featured_tags, true );
		if ( false !== $found_term ) {

			// the updated term is a featured tag! replace it in the array, save the new array.
			$featured_tags[ $found_term ] = $new_term_id;
			update_option( 'featured_tags', $featured_tags );
		}
	}
}
add_action( 'split_shared_term', 'wporg_featured_tags_split', 10, 4 );

术语 ID 存储在帖子元中

假设您的插件在页面的帖子元数据中存储术语 ID,以便您可以显示特定页面的相关帖子。

在这种情况下,您需要使用该get_posts()函数来获取您的页面meta_key并更新meta_value匹配的拆分术语 ID。


功能wp_get_split_term_

笔记:使用split_shared_term挂钩是处理术语 ID 更改的首选方法。

 

但是,在某些情况下,术语可能会被拆分,而您的插件没有机会挂钩该split_shared_term操作。

WordPress 4.2 存储有关已拆分的分类术语的信息,并提供wp_get_split_term()实用函数来帮助开发人员检索此信息。

考虑上面的情况,您的插件将术语 ID 存储在名为 的选项中featured_tags。您可能想要构建一个验证这些标签 ID 的函数(可能在插件更新时运行),以确保没有任何特色标签被拆分:


/**
 * Retrieve information about split terms and udpates the featured_tags option with the new term IDs.
 *
 * @return void
 */
function wporg_featured_tags_check_split() {
	$featured_tag_ids = get_option( 'featured_tags', array() );

	// check to see whether any IDs correspond to post_tag terms that have been split.
	foreach ( $featured_tag_ids as $index => $featured_tag_id ) {
		$new_term_id = wp_get_split_term( $featured_tag_id, 'post_tag' );

		if ( $new_term_id ) {
			$featured_tag_ids[ $index ] = $new_term_id;
		}
	}

	// save
	update_option( 'featured_tags', $featured_tag_ids );
}

请注意,它wp_get_split_term()需要两个参数,$old_term_id并且$taxonomy返回一个整数。

如果您需要检索与旧术语 ID 关联的所有拆分术语的列表,无论分类如何,请使用wp_get_split_terms()