WP_Query中tax_query的'relation'=>'AND'不生效问题排查求助
问题核心分析与修复方案
嘿,我一眼就瞅出你代码里的问题啦!你当前的tax_query完全达不到预期效果,根源出在同一个$cat变量被同时用于两个不同的分类法条件上,这就导致逻辑完全跑偏了。
为什么你的代码不生效?
咱们拆解下你的代码逻辑:
- 你用
get_the_terms( get_the_ID(), array('adcategory', 'adlocation') )把当前帖子的adcategory(广告分类)和adlocation(广告位置)两类术语都取出来混在了一起 - 经过层级处理后,
end($catsz)只拿到了这个混合数组里的最后一个ID——这个ID要么属于adcategory,要么属于adlocation,不可能同时属于两个分类法 - 当你用
relation => 'AND'时,相当于要求帖子同时属于adcategory下的这个ID,并且属于adlocation下的同一个ID,这显然不符合实际(一个分类ID不可能跨两个分类体系存在),自然查不到结果;用OR时,只有第一个分类条件可能匹配,但如果$cat是adlocation的ID,第一个条件也会失效,所以只会返回第一个条件的结果(甚至空结果)
修复后的代码
我们需要把两个分类法的逻辑分开处理,分别提取各自的层级ID,再构建正确的tax_query:
$similar = az_get_option( 'similar' ); if( !empty( $similar ) ){ // 分别获取当前帖子的「广告分类」和「广告位置」术语,不混合处理 $ad_category_terms = get_the_terms( get_the_ID(), 'adcategory' ); $ad_location_terms = get_the_terms( get_the_ID(), 'adlocation' ); // 初始化tax_query的基础结构 $tax_query_args = array( 'relation' => 'AND' ); // 处理「广告分类」的层级ID条件 if( !empty( $ad_category_terms ) ){ $category_hierarchy = az_taxonomy_hierarchy( $ad_category_terms ); $category_ids = az_taxonomy_id_hierarchy( $category_hierarchy ); $target_category = end( $category_ids ); $tax_query_args[] = array( 'taxonomy' => 'adcategory', 'terms' => array( $target_category ), 'field' => 'term_id' // 显式指定字段,避免歧义 ); } // 处理「广告位置」的层级ID条件 if( !empty( $ad_location_terms ) ){ $location_hierarchy = az_taxonomy_hierarchy( $ad_location_terms ); $location_ids = az_taxonomy_id_hierarchy( $location_hierarchy ); $target_location = end( $location_ids ); $tax_query_args[] = array( 'taxonomy' => 'adlocation', 'terms' => array( $target_location ), 'field' => 'term_id' // 显式指定字段,避免歧义 ); } // 确保至少有一个分类条件再执行查询 if( count( $tax_query_args ) > 1 ){ $ads = new WP_Query(array( 'posts_per_page' => $similar, 'post_type' => 'ad', 'post_status' => 'publish', 'tax_query' => $tax_query_args, 'orderby' => 'rand', 'post__not_in' => array( get_the_ID() ) )); if( $ads->have_posts() ){ // 这里写你的帖子循环逻辑 } } }
额外注意事项
- 显式添加
'field' => 'term_id':虽然WP默认是按term_id匹配,但显式声明可以避免因函数返回值类型变化导致的潜在问题 - 增加条件判断:确保至少有一个分类条件时才执行查询,避免空的
tax_query引发意外结果 - 分类法分离处理:彻底避免不同分类体系的ID混淆,保证逻辑的准确性
内容的提问来源于stack exchange,提问作者Edro
相关产品推荐
相关产品推荐

