I just built a site with a few CPTs (apple, banana, cucumber). My boss wanted to split them out into categories (red, yellow, green) and link to the category pages. As soon as we did and accessed the page via category in the URL, the page is not displaying correctly.
Specifically, mysite.com/category/red
is displaying the correct category, but I have WP_Query
pulling in another post type in a sidebar and this is now displaying the default posts instead of a CPT.
Every other page on the site is fine except /category
. And it behaves this way if I use archive.php
or category.php
as the template. Any idea why?
I should mention that I added the below to my functions.php
to get the CPTs to show on /category in the first place.
function query_post_type($query) {
if ( ! is_admin() ) {
if( is_category() || is_tag() && $query->is_main_query() && empty( $query->query_vars['suppress_filters'] ) ) {
$post_type = get_query_var('post_type');
if($post_type)
$post_type = $post_type;
else
$post_type = array( 'post','apple','banana','cucumber','nav_menu_item');
$query->set('post_type', $post_type);
}
}
}
add_action('pre_get_posts', 'query_post_type');