register_taxonomy_for_object_type()WP 3.0.0

Add an already registered taxonomy to an object type.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.03 sec (speed of light) | PHP 7.1.11, WP 4.9.8
Hooks from the function

Return

true|false. True if successful, false if not.

Usage

register_taxonomy_for_object_type( $taxonomy, $object_type );
$taxonomy(string) (required)
Name of taxonomy object.
$object_type(string) (required)
Name of the object type.

Examples

0

#1 Using the following code, we can bind tags to static WP pages.

add_action( 'init', 'post_tag_for_pages' );

function post_tag_for_pages(){
	register_taxonomy_for_object_type( 'post_tag', 'page' );
}

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.

As a result, in the admin, when editing pages, we will have a tag block, like the posts:

Notes

  • Global. WP_Taxonomy[]. $wp_taxonomies The registered taxonomies.

Changelog

Since 3.0.0 Introduced.

register_taxonomy_for_object_type() code WP 6.4.3

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;
}