You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:05:22