我无法成功地从某些类别中筛选帖子,同时从其他类别中排除帖子。当用于只包含给定类别的帖子时,该代码工作得非常好。要包含的类别是子类别,排除的类别是主类别(它们不是包含的子类别的父类别)
示例:
1) 同时使用两者category__in
和category__not_in
同时
$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)仅限使用
category__in
具有负值:
$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()){
.
.
}
最合适的回答,由SO网友:Jacob Peattie 整理而成
你可以使用Taxonomy Query, 像这样:
$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 );
这将查询第一组术语中的帖子,而不是第二组术语中的帖子。
SO网友:Max Yudin
请尝试此代码。但未测试
<?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
);
我省略了
suppress_filters
因为它不适合
WP_Query
.
也许你会想用\'include_children\' => false
(在代码中注释掉)如果您不想显示来自$cat_arr
子类别。