Wordpress - Get The Post Type A Taxonomy Is Attached To
If we peek into the global $wp_taxonomies
variable we see the associated object types.
There might be better ways to do this or even core functions, but you could try the following:
function wpse_172645_get_post_types_by_taxonomy( $tax = 'category' )
{
global $wp_taxonomies;
return ( isset( $wp_taxonomies[$tax] ) ) ? $wp_taxonomies[$tax]->object_type : array();
}
then for the default setup you get:
$out = wpse_172645_get_post_types_by_taxonomy( 'category' );
print_r( $out );
with the output:
Array
(
[0] => post
)
You can do the reverse with get_object_taxonomies
. Combine it with get_post_types
to iterate over post types to check the taxonomies registered for each.
EDIT- Here's an example that produces the same output as @birgire's function, without using dirty globals.
function wpse_172645_get_post_types_by_taxonomy( $tax = 'category' ){
$out = array();
$post_types = get_post_types();
foreach( $post_types as $post_type ){
$taxonomies = get_object_taxonomies( $post_type );
if( in_array( $tax, $taxonomies ) ){
$out[] = $post_type;
}
}
return $out;
}
There is no need to use the $wp_taxonomies
global variable directly as WordPress has the get_taxonomy()
function to access taxonomies in it ( in core since version 2.3.0). Since WordPress 4.7.0 the return type is a WP_Taxonomy
object with the property $object_type
$taxonomy = get_taxonomy( 'category' );
print_r( $taxonomy->object_type );