The register_taxonomy_for_object_type() WordPress PHP function adds an already registered taxonomy to an object type.
Usage
register_taxonomy_for_object_type( $taxonomy, $object_type );
Parameters
$taxonomy
(string) – The name of the taxonomy object.$object_type
(string) – The name of the object type.
More information
See WordPress Developer Resources: register_taxonomy_for_object_type()
Important: Do not forget to use the init
hook to run this function. If not, the taxonomy and/or the Custom Post Type you want to reference might not have been created yet.
Examples
Sharing ‘category’ taxonomy with ‘page’ object type
This example shares the ‘category’ taxonomy with the ‘page’ object type, allowing pages to have categories.
function share_category_with_pages() { register_taxonomy_for_object_type( 'category', 'page' ); } add_action( 'init', 'share_category_with_pages' );
Assigning ‘post_tag’ taxonomy to a Custom Post Type ‘products’
In this example, the ‘post_tag’ taxonomy is assigned to the Custom Post Type ‘products’, enabling tags for products.
function add_tags_to_products() { register_taxonomy_for_object_type( 'post_tag', 'products' ); } add_action( 'init', 'add_tags_to_products' );
Sharing a custom taxonomy ‘colors’ with the ‘post’ object type
This example shares a custom taxonomy named ‘colors’ with the ‘post’ object type, allowing posts to have colors.
function share_colors_with_posts() { register_taxonomy_for_object_type( 'colors', 'post' ); } add_action( 'init', 'share_colors_with_posts' );
Assigning multiple taxonomies to a Custom Post Type ‘events’
In this example, both ‘category’ and ‘post_tag’ taxonomies are assigned to the Custom Post Type ‘events’.
function add_taxonomies_to_events() { register_taxonomy_for_object_type( 'category', 'events' ); register_taxonomy_for_object_type( 'post_tag', 'events' ); } add_action( 'init', 'add_taxonomies_to_events' );
Sharing a custom taxonomy ‘locations’ with the ‘page’ object type
This example shares a custom taxonomy named ‘locations’ with the ‘page’ object type, allowing pages to have locations.
function share_locations_with_pages() { register_taxonomy_for_object_type( 'locations', 'page' ); } add_action( 'init', 'share_locations_with_pages' );