如何在自定义文章类型查询中排除当前文章与指定分类
自定义产品相关查询解决方案
需求说明
在single-product.php模板中,基于自定义文章类型product和分类法product-cat实现相关产品查询,需满足:
- 展示与当前产品同分类的产品
- 排除当前正在展示的产品
- 排除带有
new-and-best-seller分类的产品(部分产品存在多分类,需避免误筛)
修改后的完整代码
<?php // 获取当前产品的分类ID数组 $productCats = get_the_terms($post->ID, 'product-cat'); $productCats_ids = wp_list_pluck($productCats, 'term_id'); // 获取需要排除的分类ID(通过slug获取) $exclude_term = get_term_by('slug', 'new-and-best-seller', 'product-cat'); $exclude_term_id = $exclude_term ? $exclude_term->term_id : 0; ?> <?php $relatedProducts = new WP_Query(array( 'post_type' => 'product', 'post__not_in' => array(get_the_ID()), // 排除当前产品 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'product-cat', 'field' => 'id', 'terms' => $productCats_ids, 'operator' => 'IN', ), array( 'taxonomy' => 'product-cat', 'field' => 'id', 'terms' => $exclude_term_id, 'operator' => 'NOT IN', ) ), )); if ($relatedProducts->have_posts()) { ?> <section id="newest-products" class="mb-section"> <div class="container"> <h1 class="main__title"> <strong class="main__title--bold">Related products</strong> </h1> <div class="newest-products-wrapper owl-carousel owl-theme"> <?php while ($relatedProducts->have_posts()) { $relatedProducts->the_post(); ?> <div class="card product-card"> <?php the_post_thumbnail('medium', array('class' => 'card-img-top product-card--img')); ?> <div class="card-body"> <h2 class="card-title product-card--title"><?php esc_html(the_title()); ?></h2> <a href="<?php esc_url(the_permalink()); ?>" class="product-card--more">See available items</a> </div> </div> <?php } wp_reset_postdata(); ?> </div> </div> </section> <?php } ?>
关键修改点
- 排除当前产品:添加
post__not_in参数,传入当前产品ID,直接排除当前展示的文章 - 正确排除指定分类:
- 通过
get_term_by根据分类slug获取目标分类ID,避免硬编码ID - 在
tax_query中添加NOT IN条件,配合relation => 'AND',确保产品同时满足「属于当前分类」和「不属于排除分类」两个条件,不会误筛带有多分类的产品
- 通过
- 移除无效参数:删除原代码中针对默认文章分类的
category__not_in,该参数不适用于自定义分类法product-cat
内容的提问来源于stack exchange,提问作者Alipvd
相关产品推荐
相关产品推荐

