How to filter by custom post type in taxonomy archive pages

I have two custom types. One called “Questions” and other called “Files”. They both share a custom taxonomy called “Types”. Everything works fine, however if I go to the “Types” link inside my WordPress admin and click on any category, it lists all the items, both in “Questions” and “Files”.

Is there a way to construct a link so I could just query a specific type of one custom type instead of both?

Read More

Thanks a lot!

Related posts

1 comment

  1. That is the normal behaviour. If you go the archive of one taxonomy term you will get all posts, of any type, with this taxonomy term.

    One solution can be, for example, adding ?custom_type=files or ?custom_type=questions to your URLs and alter the main query in the pre_get_posts filter:

    add_action( 'pre_get_posts', 'my_pre_get_post' );
    function my_pre_get_post($query){
        if(!empty($_GET['custom_type'])){
    
           //limit the filter to frontend, main query and archive pages
           if($query->is_main_query() && !is_admin() && $query->is_archive ) {
    
              $query->set('post_type',sanitize_text_field($_GET['custom_type']));
    
           }
    
         }
    }
    

    If you want to go further you can write custom rewrite rules and add query vars to have those URLs be “pretty”.

Comments are closed.