0

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');

1 Answer 1

2

Your condition is off and will always be true on category pages due to how logic operators work.

This might be more clear if I write what is happening like this:

is_category() || ( is_tag() &&  $query->is_main_query() )

Once is_category() is determined to be true the rest of condition doesn't matter.

You should be more precise with your logic, along the lines of (brackets matter!):

$query->is_main_query() && ( $query->is_category() || $query->is_tag() )
1
  • Yup. That was it. Thanks! You don't know how long this has been bedeviling me.
    – jkd540
    May 12, 2016 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.