如何修改WP_Query参数同时筛选Post与Product分类?
解决方案
你的问题出在同时使用cat和product_cat参数时,WP_Query会默认用AND逻辑过滤内容,要求所有结果同时满足这两个分类条件——但post类型没有product_cat分类,product类型也没有category分类,所以没有内容能匹配。
正确的做法是使用tax_query,通过relation设置OR逻辑,分别为两种post类型指定对应的分类筛选规则:
$args = array( 'post_type' => array( 'product', 'post' ), 'posts_per_page' => 999, 'orderby' => 'meta_value_num', 'meta_key' => 'score_value', 'order' => 'DESC', 'tax_query' => array( 'relation' => 'OR', // 筛选分类ID为82、85的post array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array(82, 85), 'include_children' => false, // 可选:是否包含子分类,按需设置 ), // 筛选分类ID为96的product array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => 96, 'include_children' => false, // 可选:是否包含子分类,按需设置 ), ), ); $custom_query = new WP_Query($args);
关键说明
relation => 'OR':表示两个分类条件满足任意一个即可- 两个子数组分别对应
category(post的分类)和product_cat(WooCommerce产品的分类)的筛选规则 field => 'term_id':指定用分类ID来筛选,也可以换成slug用分类别名筛选include_children:如果不需要包含子分类的内容,可以设为false,反之设为true或省略
内容的提问来源于stack exchange,提问作者Magnus Schmidt
相关产品推荐
相关产品推荐

