Why are posts from custom post type not displayed in “category” archive?

I’ve created multiple custom post types which should share “category”.

Creation is done like this:

 $args = array(
        'label'               => __('MyPostType', 'key'),
        'description'         => __('MyPostType', 'key'),
        'labels'              => $labels,
        'supports'            => array('title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'trackbacks', 'revisions', 'custom-fields'),
        'taxonomies'          => array('category'),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_position'       => 5,
        'menu_icon'           => 'dashicons-admin-tools',
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => true,
        'can_export'          => true,
        'has_archive'         => 'techblog',
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'capability_type'     => 'post',
        'rewrite'             => $rewrite
    );

register_post_type('myposttype', $args);

This works like expected and I’m able to use categories globally.

The Problem

The categories archive only shows posts from “post”. If there is no post it only says “nothing found”.
Within the single posts meta information the posts categories are listed. I can click them, and get a “nothing found” page.

Unfortunately the documentation says nothing about this. Do I need to do something else? I thought this should work out of the box.

1
1

You need to hook into the query because the category archive page explicitly only includes the ‘post’ type and nothing else.

function namespace_add_custom_types( $query ) {
  if( (is_category() || is_tag()) && $query->is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
    $query->set( 'post_type', array(
     'post', 'myposttime'
        ));
    }
}
add_action( 'pre_get_posts', 'namespace_add_custom_types' );

Modified from this article on CSS Tricks.

Leave a Comment