1. 首页
  2. WordPress 函数手册
  3. rest

register_taxonomy()

register_taxonomy( string $taxonomy, array|string $object_type, array|string $args = array() )

创建或修改分类对象。
Creates or modifies a taxonomy object.

目录锚点:#说明#参数#返回#源码#笔记


说明(Description)

注意:不要在“init”钩子之前使用。

基于给定参数创建或修改分类对象的简单函数。如果修改现有的分类对象,请注意原始注册中的$object_type值将被覆盖。


参数(Parameters)

参数 类型 必填 说明
$taxonomy (string) 必需 分类键,不能超过32个字符。
$object_type (array | string) 必需 对象类型或对象类型数组,分类法应与之关联。
$args (array | string) 可选 用于注册分类法的参数数组或查询字符串labels’(array)此分类法的标签数组。默认情况下,标记标签用于非层次分类法,类别标签用于层次分类法。请参见get_taxonomy_labels()中的接受值。
‘description'(string) A short descriptive summary of what the taxonomy is for. ‘public’(bool) Whether a taxonomy is intended for use publicly either via the admin interface or by front-end users. The default settings of $publicly_queryable, $show_ui, and $show_in_nav_menus are inherited from $public. 可选 “分层”(bool)分类法是否是分层的。默认为false。
‘show_ui'(bool) Whether to generate and allow a UI for managing terms in this taxonomy in the admin. If not set, the default is inherited from $public (default true). ‘show_in_menu’(bool) Whether to show the taxonomy in the admin menu. If true, the taxonomy is shown as a submenu of the object type menu. If false, no menu is shown. $show_ui must be true. If not set, default is inherited from $show_ui (default true). 可选 “show_in_rest”(bool)是否在rest API中包含分类法。将此值设置为true,以使分类法在块编辑器中可用。
‘rest_base'(string) To change the base url of REST API route. Default is $taxonomy. ‘rest_controller_class’(string) REST API Controller class name. Default is ‘WP_REST_Terms_Controller’. 可选 “show_in_quick_edit”(bool)是否在“快速/批量编辑”面板中显示分类法。如果未设置,则默认值继承自$show_ui(默认值为true)。
‘show_admin_column'(bool) Whether to display a column for the taxonomy on its post type listing screens. Default false. ‘meta_box_cb’(bool | callable) Provide a callback function for the meta box display. If not set, post_categories_meta_box() is used for hierarchical taxonomies, and post_tags_meta_box() is used for non-hierarchical. If false, no meta box is shown. 可选 此分类法的“功能”(数组)功能数组。
‘manage_terms'(string) Default ‘manage_categories’. ‘edit_terms’(string) Default ‘manage_categories’. 可选 ‘assign_terms’(字符串)默认’edit_posts’。
‘rewrite'(bool|array) Triggers the handling of rewrites for this taxonomy. Default true, using $taxonomy as slug. To prevent rewrite, set to false. To specify rewrite rules, an array can be passed with any of these keys: ‘slug’(string) Customize the permastruct slug. Default $taxonomy key. 可选 “hierarchical”(bool)要么是hierarchical rewrite标记要么不是。默认为false。
‘ep_mask'(int) Assign an endpoint mask. Default EP_NONE. ‘query_var’(string | bool) Sets the query var key for this taxonomy. Default $taxonomy key. If false, a taxonomy cannot be loaded at ?{query_var}={term_slug}. If a string, the query ?{query_var}={term_slug} will be valid. 可选 ‘u built in’(bool)这个分类法是一个“内置”分类法。仅供内部使用!默认为false。

返回(Return)

(WP|u Taxonomy|WP_Error)成功时注册的分类法对象,失败时注册的WP|u Error对象。


源码(Source)

/**
 * Create or modify a taxonomy object. Do not use before init.
 *
 * A simple function for creating or modifying a taxonomy object based on the
 * parameters given. The function will accept an array (third optional
 * parameter), along with strings for the taxonomy name and another string for
 * the object type.
 *
 * Nothing is returned, so expect error maybe or use taxonomy_exists() to check
 * whether taxonomy exists.
 *
 * Optional $args contents:
 *
 * - label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used.
 * - labels - An array of labels for this taxonomy.
 *     * By default tag labels are used for non-hierarchical types and category labels for hierarchical ones.
 *     * You can see accepted values in {@link get_taxonomy_labels()}.
 * - description - A short descriptive summary of what the taxonomy is for. Defaults to blank.
 * - public - If the taxonomy should be publicly queryable; //@TODO not implemented.
 *     * Defaults to true.
 * - hierarchical - Whether the taxonomy is hierarchical (e.g. category). Defaults to false.
 * - show_ui - Whether to generate a default UI for managing this taxonomy in the admin.
 *     * If not set, the default is inherited from public.
 * - show_in_menu - Whether to show the taxonomy in the admin menu.
 *     * If true, the taxonomy is shown as a submenu of the object type menu.
 *     * If false, no menu is shown.
 *     * show_ui must be true.
 *     * If not set, the default is inherited from show_ui.
 * - show_in_nav_menus - Makes this taxonomy available for selection in navigation menus.
 *     * If not set, the default is inherited from public.
 * - show_tagcloud - Whether to list the taxonomy in the Tag Cloud Widget.
 *     * If not set, the default is inherited from show_ui.
 * - show_in_quick_edit - Whether to show the taxonomy in the quick/bulk edit panel.
 *     * It not set, the default is inherited from show_ui.
 * - show_admin_column - Whether to display a column for the taxonomy on its post type listing screens.
 *     * Defaults to false.
 * - meta_box_cb - Provide a callback function for the meta box display.
 *     * If not set, defaults to post_categories_meta_box for hierarchical taxonomies
 *     and post_tags_meta_box for non-hierarchical.
 *     * If false, no meta box is shown.
 * - capabilities - Array of capabilities for this taxonomy.
 *     * You can see accepted values in this function.
 * - rewrite - Triggers the handling of rewrites for this taxonomy. Defaults to true, using $taxonomy as slug.
 *     * To prevent rewrite, set to false.
 *     * To specify rewrite rules, an array can be passed with any of these keys
 *         * 'slug' => string Customize the permastruct slug. Defaults to $taxonomy key
 *         * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true.
 *         * 'hierarchical' => bool Either hierarchical rewrite tag or not. Defaults to false.
 *         * 'ep_mask' => const Assign an endpoint mask.
 *             * If not specified, defaults to EP_NONE.
 * - query_var - Sets the query_var key for this taxonomy. Defaults to $taxonomy key
 *     * If false, a taxonomy cannot be loaded at ?{query_var}={term_slug}
 *     * If specified as a string, the query ?{query_var_string}={term_slug} will be valid.
 * - update_count_callback - Works much like a hook, in that it will be called when the count is updated.
 *     * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms
 *       that the objects are published before counting them.
 *     * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links.
 * - _builtin - true if this taxonomy is a native or "built-in" taxonomy. THIS IS FOR INTERNAL USE ONLY!
 *
 * @todo Document $args as a hash notation.
 *
 * @since 2.3.0
 * @since 4.2.0 Introduced `show_in_quick_edit` argument.
 *
 * @global array $wp_taxonomies Registered taxonomies.
 * @global WP    $wp            WP instance.
 *
 * @param string       $taxonomy    Taxonomy key, must not exceed 32 characters.
 * @param array|string $object_type Name of the object type for the taxonomy object.
 * @param array|string $args        See optional args description above.
 * @return WP_Error|void WP_Error, if errors.
 */
function register_taxonomy( $taxonomy, $object_type, $args = array() ) {
	global $wp_taxonomies, $wp;

	if ( ! is_array( $wp_taxonomies ) )
		$wp_taxonomies = array();

	$defaults = array(
		'labels'                => array(),
		'description'           => '',
		'public'                => true,
		'hierarchical'          => false,
		'show_ui'               => null,
		'show_in_menu'          => null,
		'show_in_nav_menus'     => null,
		'show_tagcloud'         => null,
		'show_in_quick_edit'	=> null,
		'show_admin_column'     => false,
		'meta_box_cb'           => null,
		'capabilities'          => array(),
		'rewrite'               => true,
		'query_var'             => $taxonomy,
		'update_count_callback' => '',
		'_builtin'              => false,
	);
	$args = wp_parse_args( $args, $defaults );

	if ( empty( $taxonomy ) || strlen( $taxonomy ) > 32 ) {
		_doing_it_wrong( __FUNCTION__, __( 'Taxonomy names must be between 1 and 32 characters in length.' ), '4.2' );
		return new WP_Error( 'taxonomy_length_invalid', __( 'Taxonomy names must be between 1 and 32 characters in length.' ) );
	}

	if ( false !== $args['query_var'] && ! empty( $wp ) ) {
		if ( true === $args['query_var'] )
			$args['query_var'] = $taxonomy;
		else
			$args['query_var'] = sanitize_title_with_dashes( $args['query_var'] );
		$wp->add_query_var( $args['query_var'] );
	}

	if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
		$args['rewrite'] = wp_parse_args( $args['rewrite'], array(
			'with_front' => true,
			'hierarchical' => false,
			'ep_mask' => EP_NONE,
		) );

		if ( empty( $args['rewrite']['slug'] ) )
			$args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy );

		if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] )
			$tag = '(.+?)';
		else
			$tag = '([^/]+)';

		add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" );
		add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] );
	}

	// If not set, default to the setting for public.
	if ( null === $args['show_ui'] )
		$args['show_ui'] = $args['public'];

	// If not set, default to the setting for show_ui.
	if ( null === $args['show_in_menu' ] || ! $args['show_ui'] )
		$args['show_in_menu' ] = $args['show_ui'];

	// If not set, default to the setting for public.
	if ( null === $args['show_in_nav_menus'] )
		$args['show_in_nav_menus'] = $args['public'];

	// If not set, default to the setting for show_ui.
	if ( null === $args['show_tagcloud'] )
		$args['show_tagcloud'] = $args['show_ui'];

	// If not set, default to the setting for show_ui.
	if ( null === $args['show_in_quick_edit'] ) {
		$args['show_in_quick_edit'] = $args['show_ui'];
	}

	$default_caps = array(
		'manage_terms' => 'manage_categories',
		'edit_terms'   => 'manage_categories',
		'delete_terms' => 'manage_categories',
		'assign_terms' => 'edit_posts',
	);
	$args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] );
	unset( $args['capabilities'] );

	$args['name'] = $taxonomy;
	$args['object_type'] = array_unique( (array) $object_type );

	$args['labels'] = get_taxonomy_labels( (object) $args );
	$args['label'] = $args['labels']->name;

	// If not set, use the default meta box
	if ( null === $args['meta_box_cb'] ) {
		if ( $args['hierarchical'] )
			$args['meta_box_cb'] = 'post_categories_meta_box';
		else
			$args['meta_box_cb'] = 'post_tags_meta_box';
	}

	$wp_taxonomies[ $taxonomy ] = (object) $args;

	// register callback handling for metabox
 	add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' );

	/**
	 * Fires after a taxonomy is registered.
	 *
	 * @since 3.3.0
	 *
	 * @param string       $taxonomy    Taxonomy slug.
	 * @param array|string $object_type Object type or array of object types.
	 * @param array        $args        Array of taxonomy registration arguments.
	 */
	do_action( 'registered_taxonomy', $taxonomy, $object_type, $args );
}
更新版本 源码位置 使用 被使用
5.4.0 wp-includes/taxonomy.php:414 1 function 7

笔记(Notes)

如果希望分类面板在块编辑器的侧栏中可见,则应将show_in_rest设置为true。
注意不要为slug、query_var或$taxonomy name使用保留字。有关它们的列表,请参见WP_Query。
注意,分类名称(上面的$taxonomy参数)应该只包含字符a-z0-9。当你注册一个有大写字母的分类法时,它可能会起作用。但是在WP中有很多地方分类slug是通过sanitize_key()运行的(比如在AJAX标记搜索期间),这将导致微妙的破坏。

register_taxonomy() 为WP2原创文章,链接:https://www.wp2.cn/functions/register_taxonomy/

发表评论

邮箱地址不会被公开。