I’m coding a breadcrumb and I want to return the CPT name in front of the first taxonomy term.
My website’s structure is like the following:
- CPT name
- Taxonomy Term
- Taxonomy Child Term
- Post Archive of the articles from the CPT and the two terms
If the user is in the Archive, the Breadcrumb should say:
Home > CPT name > Parent Term > Child Term
I’m currently able to return the parent and child terms, but how do I return the post type name? I have on custom taxonomy for each custom post type, so if would be cool if I could get the post type by a function like this:
global $wp_query;
$term_obj = $wp_query->get_queried_object();
$thisTerm = $term_obj->term_id;
$thisTerm = get_term( $thisTerm );
$postType = get_category($thisTerm->posttype);
I know that the term object does not have a posttype
-key, but I could get the taxonomy like this. Is there a possibility to get the post type by entering the taxonomy which is registered to it?
1 Answer
On StackOverflow user indextwo suggests to do the following:
Use the get_taxonomy( $taxonomy-slug )
function which returns an object that contains all the associated post types. As suggested in the comments, we can then use get_post_type_object( $post-type-slug )
to get the object and Singular Label.
$post_type_names = array(); // Array( 'post-type-slug' => 'Post Type Label' );
$taxonomy = get_query_var( 'taxonomy' );
if( ! empty( $taxonomy ) ) {
$tax_object = get_taxonomy( $taxonomy );
$cpt_array = $tax_object->object_type;
if( ! empty( $cpt_array ) ) {
$post_type_names = array_flip( $cpt_array );
foreach( $post_type_names as $cpt_slug => $tmp ) {
$post_type_names[ $cpt_slug ] = get_post_type_object( $cpt_slug )->labels->singular_name;
}
}
}
The above will return the post type slugs in a generic Array.
Array(
[post-type-slug] => 'Post Type Name',
[post-type-slug2] => 'Post Type Name 2',
)