is_object_in_taxonomy()WP 3.0.0

Determine if the given object type is associated with the given taxonomy.

1 time — 0.000029 sec (very fast) | 50000 times — 0.24 sec (very fast) | PHP 7.1.1, WP 4.7.2

No Hooks.

Return

true|false. True if object is associated with the taxonomy, otherwise false.

Usage

is_object_in_taxonomy( $object_type, $taxonomy );
$object_type(string) (required)
Object type string.
$taxonomy(string) (required)
Single taxonomy name.

Examples

0

#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
}
0

#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() code WP 6.1.1

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