如何在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_queryusesrelation => 'AND', which means two main conditions have to be satisfied:- The product is definitely in the
redcategory. - The product is in either
hardorsoftcategory (handled by the nestedORgroup).
- The product is definitely in the
- 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
相关产品推荐
相关产品推荐

