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');
        $post_type = $post_type;
        $post_type = array('post','cpt'); // replace cpt to your custom 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.


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) {
    && ( is_category() || is_tag() )) {
        $query->set( 'post_type', array('post','cpt') );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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