函数文档

unregister_taxonomy_for_object_type()

💡 云策文档标注

概述

unregister_taxonomy_for_object_type() 函数用于从对象类型中移除已注册的分类法,例如从文章类型中移除标签或分类。它接受分类法和对象类型作为参数,返回布尔值表示操作是否成功。

关键要点

  • 参数:$taxonomy(字符串,必需)为分类法名称,$object_type(字符串,必需)为对象类型名称。
  • 返回值:成功时返回 true,失败时返回 false。
  • 功能:检查分类法和对象类型是否存在,从全局 $wp_taxonomies 数组中移除关联,并触发 unregistered_taxonomy_for_object_type 钩子。
  • 钩子:do_action('unregistered_taxonomy_for_object_type', $taxonomy, $object_type) 在移除后触发。
  • 相关函数:包括 get_post_type_object() 和 WP_Post_Type::unregister_taxonomies()。
  • 版本:自 WordPress 3.7.0 引入。

代码示例

function wpdocs_unregister_tags_for_posts() {
    unregister_taxonomy_for_object_type( 'post_tag', 'post' );
}
add_action( 'init', 'wpdocs_unregister_tags_for_posts' );

注意事项

  • 用户贡献笔记中提到,在 PHP 8 环境下使用此函数可能导致 WordPress 后台出现“Undefined array key”警告,需注意兼容性问题。
  • 移除分类法可能影响管理界面,如移除标签菜单项、列和元框。

📄 原文内容

Removes an already registered taxonomy from an object type.

Parameters

$taxonomystringrequired
Name of taxonomy object.
$object_typestringrequired
Name of the object type.

Return

bool True if successful, false if not.

Source

function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) {
	global $wp_taxonomies;

	if ( ! isset( $wp_taxonomies[ $taxonomy ] ) ) {
		return false;
	}

	if ( ! get_post_type_object( $object_type ) ) {
		return false;
	}

	$key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true );
	if ( false === $key ) {
		return false;
	}

	unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] );

	/**
	 * Fires after a taxonomy is unregistered for an object type.
	 *
	 * @since 5.1.0
	 *
	 * @param string $taxonomy    Taxonomy name.
	 * @param string $object_type Name of the object type.
	 */
	do_action( 'unregistered_taxonomy_for_object_type', $taxonomy, $object_type );

	return true;
}

Hooks

do_action( ‘unregistered_taxonomy_for_object_type’, string $taxonomy, string $object_type )

Fires after a taxonomy is unregistered for an object type.

Changelog

Version Description
3.7.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Below is an example of how you can entirely remove tags from use for blog posts. This code will remove the Tags admin menu item, the Tags column when viewing the list of posts and the Tags metabox when editing a single post.

    function wpdocs_unregister_tags_for_posts() {
        unregister_taxonomy_for_object_type( 'post_tag', 'post' );
    }
    add_action( 'init', 'wpdocs_unregister_tags_for_posts' );

  2. Skip to note 4 content

    function wpdocs_unregister_tags_for_posts() {
        unregister_taxonomy_for_object_type( 'post_tag', 'post' );
    }
    add_action( 'init', 'wpdocs_unregister_tags_for_posts' );

    Needed to remove category from the default post but I get an “undefined offset: 2” error when I use the above code. Is it that this function is no longer in core or are there aspects to it that’re missing?