I've played around for hours but still can't wrap my head around the right arguments for a secondary WP_Query which shall fetch all posts of my_custom_post_type that are in the queried category.

Scenario is a custom category.php template file (writing a custom theme) to render a category archive for custom post type posts. Hence, the main query is by category name / slug retrieved from the URL (e.g. /category/cat-name). By default, the main query doesn't fetch custom post type posts, though. Please note, I use the default category taxonomy with my custom post type.

So, I am looking for something like

$args = array(
  'post_type' => 'my_custom_post_type',
  'category_id'  => $current_category_id

However, how to get $current_category_id from the main query? Or, how to do it the right way?


If you want your main query to take in account your custom post type, you can do as shown below :

function add_custom_post_type_to_query( $query ) {
    if ( $query->is_archive() && $query->is_main_query() ) {
        $query->set( 'post_type', array('post', 'my_custom_post_type') );
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );

You can place the above code in your theme's functions.php or in a plugin.

In order to get the current taxonomy term id (here the taxonomy is the default "category" taxonomy), you can use the following line of code :


(taken from here)

Since you are talking about custom post type, you'll probably use custom taxonomy one day as well. To properly include some taxonomy filtering in a WP_Query, you can refer to this link

Here is a sample WP_Query with the category taxonomy :

$args = array(
    'post_type' => 'my_custom_post_type', // or multiples : array('my_custom_post_type','post')
    'tax_query' = array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => get_queried_object()->term_id,

But you'll probably never want to do a WP_Query with a tax_query on your current taxonomy term since it does it automatically (after you added the custom post type in the main query post types)

  • Awesome, I didn't know about get_queried_object() - that did the trick. I have played around with 'pre_get_posts' action hook, too. That brings up the question, when to use pre_get_posts hook vs WP_Query ... but guess, that's another one... ;) – Bunjip Jan 13 '16 at 16:32
  • In my opinion, the WP_Query is useful when you have to display some other content than the main content (ie related posts plugin, widget etc..). When you just want to display your main content, pre_get_posts seems more natural since you just have to do it once in your functions.php – Sladix Jan 13 '16 at 16:39
  • Yeah, that sounds quite reasonable to me. Thanks a lot! – Bunjip Jan 13 '16 at 16:48

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.