How to show Custom Post Type name in category archive?

How to show Custom Post Type name in category archive? I already tried with shortcode and this snippet, but it returns an empty string. I want the CPT name (plural label) or if that’s hard to do: the Post type key. Cwicly can do so much, it feels like I miss something in the dynamic side of things… Thanks!


function display_current_post_type_shortcode() {
    // Check if it's a category archive
    if (is_category() && is_archive()) {
        // Get the current category object
        $category = get_queried_object();

        // Check if the category has a custom post type associated with it
        if ($category && isset($category->taxonomy) && isset($category->term_id)) {
            $post_type = get_taxonomy($category->taxonomy)->object_type;

            if (!empty($post_type)) {
                $post_type_labels = get_post_type_object($post_type[0])->labels;
                // Return the content with the current post type
                return '<p>Current Custom Post Type in Category Archive: ' . esc_html($post_type_labels->singular_name) . '</p>';
            }
        }
    }

    // Return an empty string if not a category archive
    return 'hier CPT naam test vanuit shortcode';
}

// Register the shortcode
add_shortcode('current_post_type', 'display_current_post_type_shortcode');```

Hi,

Beware, first, is_category() should be only be used with standard posts and not CPTs.
For CPTS, just use is_archive().

And second, you can’t use the same code for both archives and taxonomies.

I use this for CPTS, main archive and tax archive:

if ( is_tax() )
  return get_post_type_object( get_post_type() )->labels->name . ' : ' . single_term_title( '', false );

if ( is_archive() )
  return post_type_archive_title('', false);
1 Like

Thank you. I adjusted the code to this and now I have what I want: just the CPT name. Thanks!

function custom_archive_info_shortcode()
{
    $output = "";

    if (is_tax()) {
        $output =
            get_post_type_object(get_post_type())->labels->name;
    } elseif (is_archive()) {
        $output = post_type_archive_title("", false);
    }

    return "<p>" . esc_html($output) . "</p>";
}

// Register the shortcode
add_shortcode("archive_info", "custom_archive_info_shortcode");

I am now in need of having the custom post type name in Search results query grid items. So somehow check every item and show that CPT name dynamically (with shortcode also fine) Any ideas?

It is the same as taxonomy, but I would use singular instead:

get_post_type_object(get_post_type())->labels->singular_name;