get_object_taxonomies()
Gets the taxonomies related to the specified post type or the passed object.
Does not make queries, but simply checks data from the global variable $wp_taxonomies.
No Hooks.
Returns
String[]|WP_Taxonomy[]
. All names or objects of taxonomies related to the specified post type or another object.
Usage
get_object_taxonomies( $object, $output = 'names' );
- $object(string/string[]/WP_Post) (required)
- The name of the post type, an array of post type names, or an object of a single post (WP_Post, $post).
- $output(string)
In what form to return the result. Can be:
names
- will return only the names of the taxonomies
objects
- will return the objects of the taxonomiesDefault: 'names'
Examples
#1 Taxonomy names for the post type
$taxonomy_names = get_object_taxonomies( 'post' ); print_r( $taxonomy_names ); /* will take it out: Array ( [0] => category [1] => post_tag [2] => post_format ) */
#2 Taxonomy objects for the post type
A similar example to the previous one that returns taxonomies related to the post type as data objects for each taxonomy:
$taxonomy_objects = get_object_taxonomies( 'post', 'objects' ); print_r( $taxonomy_objects ); /* will take it out: Array ( [category] => stdClass Object ( [hierarchical] => 1 [update_count_callback] => [rewrite] => [query_var] => category_name [public] => 1 [show_ui] => 1 [show_tagcloud] => 1 [_builtin] => 1 [labels] => stdClass Object ( ... ) ... [name] => category [label] => Categories ) [post_tag] => stdClass Object ( ... ) [post_format] => stdClass Object ( .... ) ) */
#3 Taxonomy names for the post object
To get the names of taxonomies supported by the current post, you need to pass the entire post object instead of the post type name:
add_action( 'wp_head', 'get_current_post_taxonomies' ); function get_current_post_taxonomies(){ global $post; $taxonomy_names = get_object_taxonomies( $post ); print_r( $taxonomy_names ); } /* will take it out: Array ( [0] => category [1] => post_tag [2] => post_format ) */
#4 We obtain taxonomies of several post types
Its nice to know that I can get multiple post type taxonomies at once without making a loop.
Suppose we have two types of posts with taxonomies: post (native) and mypost (custom), then:
$tax_names = get_object_taxonomies( [ 'post', 'mypost' ] ); /* $tax_names Array ( [0] => category // dachshund post [1] => post_tag // post taxa [2] => post_format // taxa post [3] => mypost_tag // mypost dachshund [4] => mypost_cat // mypost dachshund ) */
Or we can get all data as objects, but not names only:
$tax_names = get_object_taxonomies( [ 'post', 'mypost' ], 'objects' );
Notes
- Global. WP_Taxonomy[]. $wp_taxonomies The registered taxonomies.
Changelog
Since 2.3.0 | Introduced. |