WP_Query with custom post_type and cat retrieving unwanted posts with the custom posts

I have a custom post type “projets” that is using the category taxonomy (so it is sharing categories with regular posts).

When I call WP_Query like this:

$args = array(
    'post_type' => 'projets',
    'posts_per_page' => 6,
    'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
);
$projects = new WP_Query($args);

It works perfectly fine.
But when I add a category to the arguments like this:

$args = array(
    'post_type' => 'projets',
    'posts_per_page' => 6,
    'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1,
    'cat' => 39
);
$projects = new WP_Query($args);

It does not returns only projets custom post_type but also regular posts that share the category 39…
Is there a way to make sure only the custom post type will be returned?

For info I use the Custom Post Type UI extension to declare the post type, I did not declare them myself.


Edit:

To clarify after the first comments, I did not register a custom taxonomy.

I only registered a custom post type called “projets” using the CPT UI plugin, with which I linked the Categories (WP Core) built-in taxonomy.

You can have a look at this and this screenshots to see how I configured everything.

The post type name I am using with WP_Query is correct, since it does return the “projets” posts. The problem is that when I add a category to the $args, then regular posts (posts with the “post” type) are being returned.


Edit 2 and solution:

As pointed out by @krzysiek-dróżdż and @chinmoy-kumar-paul , in my theme file I am using the pre_get_posts filter :

//Add projets custom posts within the loop
function namespace_add_custom_types( $query ) {
  if( (is_category() || is_tag()) && $query->is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
    $query->set( 'post_type', array(
     'post', 'projets'
        ));
    }
    return $query;
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );

If I comment it out, the problem is gone… So the problem is found out!

But isn’t it a WordPress bug? I mean I still do want this custom post type to be included in the loop, so my problem is not completely solved.

In the end, one solution is to add $args['suppress_filters'] = true; before doing the query, allowing to avoid this filter and fix the problem.

3 Answers
3

Assuming that you have a CPT with slug projets and you’ve registered built-in categories for that CPT, it all looks correct.

So there are two possibilities, that I would check:

  1. Typos – maybe you misstyped your CPT name somewhere in your code.
  2. pre_get_posts filter is modifying your query and changing its behavior (it’s pretty common if you write pre_get_posts and don’t pay enough attention to conditions inside of it).

Leave a Comment