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

如何在WordPress中实现product_cat分类的AND+OR多条件查询

Solution for Filtering Products with Multiple Taxonomy Conditions

Got it, let's figure out how to get exactly the products you need—those that are in the red category and either hard or soft category.

The key here is nesting your tax_query to combine both AND and OR logic. Here's the complete, working code:

$args = array( 
    'post_status' => 'publish', 
    'posts_per_page' => -1, 
    'post_type' => 'product', // Don't forget to specify your custom post type!
    'tax_query' => array( 
        'relation' => 'AND', // All top-level conditions must be true
        array( 
            'taxonomy' => 'product_cat', 
            'field' => 'slug', 
            'terms' => 'red', // Product MUST be in the "red" category
        ),
        // This nested group handles the "hard OR soft" requirement
        array(
            'relation' => 'OR', // At least one of these must be true
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => 'hard',
            ),
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => 'soft',
            ),
        )
    ) 
);

// Run the query to get your products
$filtered_products = new WP_Query( $args );

How this works:

  • The outer tax_query uses relation => 'AND', which means two main conditions have to be satisfied:
    1. The product is definitely in the red category.
    2. The product is in either hard or soft category (handled by the nested OR group).
  • I added post_type => 'product' to make sure WordPress targets your custom post type—easy to miss but essential!

If you need to expand this later (like adding more categories to the OR group), just add another array inside the nested OR block with the new slug.

内容的提问来源于stack exchange,提问作者Abilash Erikson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:24:43