Include posts from some categories while excluding from others
-
22-02-2021 - |
Question
I cannot successfully filter posts from some categories and exclude at the same time from others. The code is working perfectly when used to include only posts from a given category. Categories to be included are subcategories and the excluded categories are main categories (they're not parents to the included subcategories)
Examples:
1) Use both category__in
and category__not_in
at the same time
$wpid = get_category_id($_REQUEST['param']);
$cat_arr = array($wpid);
$args = array(
'category__in' => $cat_arr,
'category__not_in' => array(350,351),
'posts_per_page' => 10,
'post_status' => 'publish',
'suppress_filters' => 0
);
$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}
2) Use only category__in
with negative values:
$wpid = get_category_id($_REQUEST['param']);
$cat_arr = array($wpid);
array_push($cat_arr, -350, -351);
$args = array(
'category__in' => $cat_arr,
'posts_per_page' => 10,
'post_status' => 'publish',
'suppress_filters' => 0
);
$the_query = new WP_Query( $args );
while ($the_query -> have_posts()){
.
.
}
Solution
You could use a Taxonomy Query, like so:
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'terms' => array(),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'terms' => array(),
'operator' => 'NOT IN',
),
),
);
$query = new WP_Query( $args );
This will query posts that are in the first set of terms AND not in the second set.
OTHER TIPS
Try this code. Not tested though
<?php
$args = array(
'tax_query' => array(
'relation' => 'AND', // logical relationship between taxonomy arrays
array( // subcategories to exclude
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array(350, 351),
'operator' => 'NOT IN', // exclude
'post_parent' => 0 // top level only
),
array( // categories to include
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array($cat_arr),
// 'include_children' => false
)
),
'posts_per_page' => 10,
// more lines if needed
);
I omited suppress_filters
because it is not appropriate with WP_Query
.
May be you'll want to use 'include_children' => false
(commented out in the code) if you don't want to show posts from $cat_arr
subcategories.