Show Custom Post Types in Category Archive Page

By default WordPress custom post types do not appear in a category or tag archive page, to change this behaviour and display the custom post type you can add this filter/function to your themes functions.php file.

function themeprefix_show_cpt_archives( $query ) {
 if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
 $query->set( 'post_type', array(
 'post', 'nav_menu_item', 'custom-post-type-name'
 ));
 return $query;
 }
}
add_filter( 'pre_get_posts', 'themeprefix_show_cpt_archives' );

Jus add your custom post type name to suit, or to add more than one just comma separate the names.

This uses the pre_get_posts filter – Ref

4 Comments

  1. Steve on May 17, 2016 at 5:06 pm

    Just an FYI that you should not pass an array of post types to $query->set(‘post_type’,array()) because it will throw an error/notice in php and cause issues with certain functionality. The second argument must be string/scalar.

    Take a look at: https://core.trac.wordpress.org/attachment/ticket/30013/30013.3.diff

  2. Eric on July 7, 2015 at 3:20 pm

    Great! I stumbled across this post and it is a great help, thanks. BUT, there are some glitches with Recent Posts widget and nav menus (and I haven’t worked out how to fix them yet):

    In the archive view *with* ‘nav_menu_items’ in the query: the Recent Posts widget shows nav items (e.g. ‘Home’ and ‘Blog’ pages) which I don’t want.

    In the archive view *without* ‘nav_menu_items’ in the query: Recent Posts is right but these items are not shown on the nav menu, breaking the navigation.

    Also, CPT entries are listed in Recent Posts widget when viewing it on archive pages, but when viewing on other pages like the entry itself or the home/blog feed.

    In the hope that you’re still monitoring comments on this post can you give me any tweaks to fix this? 🙂

  3. Glenn Dixon on March 20, 2015 at 8:04 pm

    Neil,

    I just spent HOURS in a chat room getting help from several people trying to help me work around this very issue. Was converting plain WP w/ crazy amount of products, CPT’s, taxonomies, page templates, etc. Very custom, very ugly. Your post was the missing piece! Was getting very tired of seeing the same damned blank pages. If you lived here in Mexico I’d buy you a bottle of tequila!

    Thank you!

    • Neil Gee on March 20, 2015 at 10:38 pm

      Next time I’m in Mexico I’ll hit you up.

Leave a Comment





%d bloggers like this: