Exclude or Include category ids in WP_Query

I have a wordpress setup which has more than 300 categories.

Now I have requirement to give some flexibility to choose the categories. In that case I initially pre-ticked all the categories, if someone need to exclude a category they can deselect it.

Now the problem I am facing is how to give accurate results according the category selection.

My first approach was just exclude all the deselect categories as bellow,

eg: exclude 10,11,12 categories

$args = array(
    'category__not_in' => array('10','11','12')
);

Let’s say I have a post which was ticked under category 12 & 13. From above code I will not get that post as a result as it is excluding posts under the category 12. But ideally it should be in the results as category 13 was not deselected.

As I solution I could use 'category__in' option with all selected category ids. But my worry is the list would be very long even-though it is coming programmatically, I am not sure about the wp_query overhead as I have more than 300 categories.

Anyone has a better idea how to solve this issue.

6 s
6

As you probably know it, categories are taxonomies. When you use the arguments such as category__in, it will add a tax query to your WP_Query(). So, your situation would be something like this:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => array( 12 ),
            'operator' => 'IN',
        ),
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => array( 11, 12, 13 ),
            'operator' => 'NOT IN',
        ),
    ),
);
$query = new WP_Query( $args );

I wouldn’t think of performance issues here. This is most likely your only solution, if you don’t want to directly query the posts from database by using a SQL query ( This might improve the performance a bit ).

Leave a Comment