11

Being given a taxonomy or term, is is possible to pull any / all post types the taxonomy is attached to?

For example, knowing the built in taxonomy category or being given a term in the category taxonomy, is there a function to reverse engineer that category is a taxonomy of post ?

Unneeded Info

I'm working with some custom fields in taxonomy terms that specifically need to know the post type, but if the post type parameter in the URL isn't there for whatever reason I run into trouble.

11

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.