2

I have 3 different post types in my blog. When I click on a category of a custom post, I redirect to a 404 page, because by default archive.php does not recognize custom post types.

I have found this solution (and other ones using same approach) on several different places:

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
  if(is_category() || is_tag()) {
    $post_type = get_query_var('post_type');
    if($post_type)
        $post_type = $post_type;
    else
        $post_type = array('post','cpt'); // replace cpt to your custom post type
    $query->set('post_type',$post_type);
    return $query;
    }
}

the problem is, on sidebar I also use a WP_Query loop to show lastest posts from each custom post category. This solution works perfectly for archive page, but it messes up (actually combines all my post types) with my sidebar script.

I'm looking around for a solution which does not use pre_get_posts for hours and I didn't find anything. Help would be really appreciated.

2

At the pre_get_posts action, check if the query object is_main_query to target only the main archive query and exclude additional queries.

add_action('pre_get_posts', 'query_post_type');
function query_post_type($query) {
  if($query->is_main_query()
    && ( is_category() || is_tag() )) {
        $query->set( 'post_type', array('post','cpt') );
  }
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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