is_object_in_taxonomy()
Checks if the specified post type is associated with the specified taxonomy.
In $object_type, you can specify multiple post types for checking.
No Hooks.
Returns
true|false. True - if the object is associated with the taxonomy, false - if not.
Usage
if( is_object_in_taxonomy( $object_type, $taxonomy ){
// check passed
}
- $object_type(string/array/object)
- The name of the post type, an array of post type names, or an object of a single post (the post type will be obtained from it) (WP_Post, $post).
- $taxonomy(string)
- The name of the taxonomy to check the association with (which the post type specified in $object_type should be associated with, post types, or post object).
Examples
#1 Demo
A simple check:
if( is_object_in_taxonomy( 'post', 'category' ) ){
// post type has a taxonomy category
}
Use WP_Post object as first parameter:
if( is_object_in_taxonomy( $post, 'category' ) ){
// the post type the post $post belongs to has a taxonomy category
}
Checking several types of posts at once (hard to imagine when this might be necessary, but it is possible):
if( is_object_in_taxonomy( [ 'post', 'mypost' ], 'category' ) ){
// post or mypost types have a taxonomy category
} #2 Output the list of taxonomy terms if it is related to the post type
We are making a form to add a new post type from the front-end.
Now let's assume that we don't know beforehand whether our post type is connected to a taxonomy. I.e. we have created a new post type and it may or may not have a category taxonomy attached to it.
If the taxonomy category is enabled, we need to display a drop-down list of all categories.
This code shows how to do such a check.
// output the category list if the category taxonomy
// is connected to the custom post type
$post_type = 'my_post'; // our custom post type
if( is_object_in_taxonomy( $post_type, 'category' ) ){
$dropdown_options = array(
'show_option_all' => get_taxonomy( 'category' )->labels->all_items,
'hide_empty' => 0,
'hierarchical' => 1,
'show_count' => 0,
'orderby' => 'name',
//'selected' => $cat
);
echo '<label>Select categories:</label>';
wp_dropdown_categories( $dropdown_options );
}
Changelog
| Since 3.0.0 | Introduced. |
is_object_in_taxonomy() is object in taxonomy code WP 7.0
function is_object_in_taxonomy( $object_type, $taxonomy ) {
$taxonomies = get_object_taxonomies( $object_type );
if ( empty( $taxonomies ) ) {
return false;
}
return in_array( $taxonomy, $taxonomies, true );
}