WordPress基于两个自定义分类法显示相关产品的AND关系问题
自定义文章类型相关产品筛选实现方案
问题描述
我有一个自定义文章类型(custom post type)product,以及两个自定义分类法(custom taxonomies):productfamily和industry。在单个产品页面中,需要显示属于同一productfamily且匹配当前产品任一industry的相关产品。
目前使用的代码如下:
$wp_query = new WP_Query( array( 'posts_per_page' => '4', 'post_type' => 'product', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'productfamily', 'field' => 'slug', 'terms' => $prodfam, 'operator' => 'IN' ), array( 'taxonomy' => 'industry', 'field' => 'term_id', 'terms' => $prodindustry, 'operator' => 'IN' ), ), 'orderby' => 'title', 'order' => 'ASC', ) );
若将tax_query的relation改为OR,仅能显示同productfamily的产品,完全未考虑industry条件,请问如何实现需求中的筛选逻辑?
解决方案
你的需求逻辑是必须属于同一productfamily,同时匹配当前产品的任意一个industry,原代码的relation => 'AND'逻辑方向正确,问题大概率出在分类项参数的取值或查询细节上,以下是修正方案:
1. 确保正确获取当前产品的分类项
首先要准确获取当前产品对应的productfamily和industry分类数据,避免参数为空导致查询失效:
// 获取当前产品ID $current_product_id = get_the_ID(); // 提取当前产品的productfamily分类slug $prodfam_terms = get_the_terms($current_product_id, 'productfamily'); $prodfam = !empty($prodfam_terms) ? wp_list_pluck($prodfam_terms, 'slug') : array(); // 提取当前产品的industry分类term_id $prodindustry_terms = get_the_terms($current_product_id, 'industry'); $prodindustry = !empty($prodindustry_terms) ? wp_list_pluck($prodindustry_terms, 'term_id') : array();
2. 修正后的完整查询代码
添加排除当前产品的逻辑,同时优化查询性能:
// 仅当两个分类参数都有效时执行查询 if (!empty($prodfam) && !empty($prodindustry)) { $related_products = new WP_Query( array( 'posts_per_page' => 4, 'post_type' => 'product', 'post__not_in' => array($current_product_id), // 排除当前显示的产品 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'productfamily', 'field' => 'slug', 'terms' => $prodfam, 'operator' => 'IN' ), array( 'taxonomy' => 'industry', 'field' => 'term_id', 'terms' => $prodindustry, 'operator' => 'IN' ), ), 'orderby' => 'title', 'order' => 'ASC', 'no_found_rows' => true, // 关闭分页计数,提升查询速度 ) ); // 输出相关产品列表 if ($related_products->have_posts()) { echo '<h3>相关产品</h3>'; echo '<ul>'; while ($related_products->have_posts()) { $related_products->the_post(); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; } echo '</ul>'; wp_reset_postdata(); // 重置查询,避免影响后续内容 } }
3. 排查OR逻辑无效的原因
如果切换为relation => 'OR'后仅显示同family的产品,说明$prodindustry为空数组,WP_Query会自动忽略无效的分类查询条件。请检查:
- 当前产品是否已分配
industry分类项 get_the_terms函数的参数是否正确(第二个参数是分类法的slug)
内容的提问来源于stack exchange,提问作者PurpleMonkeyDishwasher
相关产品推荐
相关产品推荐

