How to select posts from one category but exclude posts in another category?

I am trying to select posts that have category id 4 but exclude posts that also have category id 2

Here’s what i’m trying

$query = new WP_Query(array(
  "cat__in"         => array(4),
  "cat__not_in"     => array(2),
  "post_type"       => "post",
  "post_status"     => "publish",
  "orderby"         => "date",
  "order"           => "DESC",
  "posts_per_page"  => $limit,
  "offset"          => 0
));

However, it’s not making the proper selection. What am I doing wrong?

3 Answers
3

Use pre_get_posts to exclude the categories you don’t want to display in the loop.

function exclude_posts_from_specific_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '-2' );
    }
}
add_action( 'pre_get_posts', 'exclude_posts_from_specific_category' );

Or create a new WP_Query and use the Category Parameters.

<?php

$args = array( 

'category__not_in' => 2 ,

'category__in' => 4 

);

$the_query = new WP_Query( $args );


if ( $the_query->have_posts() ) {
        echo '<ul>';
        while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
        echo '</ul>';
} else {

}

wp_reset_postdata();

If you only want to display posts from one category, you would use the category archive. See Template Hierarchy.

Leave a Comment