函数文档

register_taxonomy_for_object_type()

💡 云策文档标注

概述

register_taxonomy_for_object_type() 函数用于将已注册的分类法关联到指定的对象类型(如文章类型)。它检查分类法和对象类型的有效性,并在成功关联后触发一个动作钩子。

关键要点

  • 函数参数:$taxonomy(字符串,必需)为分类法名称,$object_type(字符串,必需)为对象类型名称。
  • 返回值:成功时返回 true,失败时返回 false(例如分类法或对象类型不存在)。
  • 内部逻辑:验证分类法存在于 $wp_taxonomies 全局变量中,并检查对象类型是否已通过 get_post_type_object() 注册。
  • 钩子:关联成功后触发 registered_taxonomy_for_object_type 动作钩子,传递分类法和对象类型名称。
  • 使用场景:常用于在 init 钩子中关联分类法与自定义文章类型,确保两者已注册。

代码示例

function namespace_share_category_with_pages() {
    register_taxonomy_for_object_type( 'category', 'page' );
}
add_action( 'init', 'namespace_share_category_with_pages' );

注意事项

  • 必须在 init 钩子或之后调用此函数,以确保分类法和对象类型已创建,避免关联失败。

📄 原文内容

Adds an already registered taxonomy to 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 register_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;
	}

	if ( ! in_array( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true ) ) {
		$wp_taxonomies[ $taxonomy ]->object_type[] = $object_type;
	}

	// Filter out empties.
	$wp_taxonomies[ $taxonomy ]->object_type = array_filter( $wp_taxonomies[ $taxonomy ]->object_type );

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

	return true;
}

Hooks

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

Fires after a taxonomy is registered for an object type.

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Do not forget to use the init hook to run this function. If not, the taxonomy and / or the CPT you want to reference might not have been created yet.

    /**
     * Share taxonomy pdf-groups with posts
     *
     * @return void
     */
    function namespace_share_category_with_pages() {
    	register_taxonomy_for_object_type( 'category', 'page' );
    }
    
    add_action( 'init', 'namespace_share_category_with_pages' );