2

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 1

1

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',
)
1
  • 1
    I changed it tho this, it now returns the label: if( ! empty( $taxonomy ) ) { $tax_object = get_taxonomy( $taxonomy ); $cpt_array = $tax_object->object_type; $posttype_obj = get_post_type_object($cpt_array[0]); $posttype = $posttype_obj->label; }
    – Sam
    Feb 14, 2017 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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