Custom Post Type not visible on category page

I would like to use the default category for my custom post type, but when I open the category page there’s no posts there.

The loop is very simple:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="col-md-3 col-sm-6 col-xs-12 margin-bottom-30">
    <?php $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'product' ); ?>
        <div class="item-image"><a href="https://wordpress.stackexchange.com/questions/163901/<?php echo $large_image_url[0]; ?>" class="zoom-effect"><?php the_post_thumbnail('product', array( 'class' => 'img-full' )); ?></a></div>
    <div class="item-desc box-grey padding-all-10"><?php the_title(); ?></div>
</div>
<?php endwhile; else: ?>
    <p><?php _e('No posts were found. Sorry!'); ?></p>
<?php endif; ?>

I don’t want to use custom taxonomy. I also created the archive-{cpt}.php file for displaying all posts.

Where is the problem?

2 Answers
2

Custom post types are excluded from the main query by default (except on taxonomy pages and custom post type archive pages), that is why you don’t see posts from your custom post type on your category page.

You need to include your custom post type posts in the main query manually. That is done with pre_get_posts which alters the main query before it is executed.

You can do the following to include your custom post type on category pages

function custom_post_type_cat_filter($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_category()) {
      $query->set( 'post_type', array( 'post', 'YOUR CPT' ) );
    }
  }
}

add_action('pre_get_posts','custom_post_type_cat_filter');

Leave a Comment