函数文档

unregister_taxonomy()

💡 云策文档标注

概述

unregister_taxonomy() 函数用于注销一个自定义分类法,但不可用于注销内置分类法。它返回 true 表示成功,或 WP_Error 表示失败。

关键要点

  • 函数用于注销自定义分类法,内置分类法(如 category 或 post_tag)无法注销。
  • 参数 $taxonomy 为字符串,必需,指定要注销的分类法名称。
  • 返回值:成功时返回 true,失败或分类法不存在时返回 WP_Error。
  • 注销前会检查分类法是否存在,并移除相关的重写规则和钩子。
  • 注销后会触发 unregistered_taxonomy 动作钩子。

代码示例

add_action( 'init', 'wpname_unregister_taxonomy' );

function wpname_unregister_taxonomy() {
    unregister_taxonomy( 'product_category');
}

注意事项

  • 确保在适当的钩子(如 init)中调用此函数,以避免过早执行。
  • 注销分类法前,应确认其非内置,否则会返回错误。

📄 原文内容

Unregisters a taxonomy.

Description

Can not be used to unregister built-in taxonomies.

Parameters

$taxonomystringrequired
Taxonomy name.

Return

true|WP_Error True on success, WP_Error on failure or if the taxonomy doesn’t exist.

Source

function unregister_taxonomy( $taxonomy ) {
	global $wp_taxonomies;

	if ( ! taxonomy_exists( $taxonomy ) ) {
		return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
	}

	$taxonomy_object = get_taxonomy( $taxonomy );

	// Do not allow unregistering internal taxonomies.
	if ( $taxonomy_object->_builtin ) {
		return new WP_Error( 'invalid_taxonomy', __( 'Unregistering a built-in taxonomy is not allowed.' ) );
	}

	$taxonomy_object->remove_rewrite_rules();
	$taxonomy_object->remove_hooks();

	// Remove the taxonomy.
	unset( $wp_taxonomies[ $taxonomy ] );

	/**
	 * Fires after a taxonomy is unregistered.
	 *
	 * @since 4.5.0
	 *
	 * @param string $taxonomy Taxonomy name.
	 */
	do_action( 'unregistered_taxonomy', $taxonomy );

	return true;
}

Hooks

do_action( ‘unregistered_taxonomy’, string $taxonomy )

Fires after a taxonomy is unregistered.

Changelog

Version Description
4.5.0 Introduced.

User Contributed Notes