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

求助:WooCommerce子分类关联商品如何排除当前商品

解决WooCommerce关联商品排除当前商品的问题

刚好碰到过类似的需求,给你两个稳妥的解决方案,根据你的实际实现情况来选:

方案一:用官方钩子修改关联商品查询(推荐)

如果你是通过WooCommerce默认的关联商品逻辑调整的范围,直接用woocommerce_product_related_posts_query这个官方钩子来修改查询参数,就能轻松排除当前商品:

add_filter( 'woocommerce_product_related_posts_query', 'exclude_current_product_from_related_products', 10, 2 );
function exclude_current_product_from_related_products( $query_args, $product ) {
    // 给查询添加排除当前商品ID的条件
    $query_args['post__not_in'] = array( $product->get_id() );
    
    return $query_args;
}

补充说明:

  • 把这段代码添加到你当前主题的functions.php文件里,或者用专门的代码片段插件(比如Code Snippets)来添加,避免主题更新时丢失代码。
  • 如果你的代码里已经有其他修改post__not_in的逻辑,改成下面的写法更稳妥,防止覆盖已有排除规则:
add_filter( 'woocommerce_product_related_posts_query', 'exclude_current_product_from_related_products', 10, 2 );
function exclude_current_product_from_related_products( $query_args, $product ) {
    // 合并已有排除规则和当前商品ID
    if ( isset( $query_args['post__not_in'] ) ) {
        $query_args['post__not_in'][] = $product->get_id();
    } else {
        $query_args['post__not_in'] = array( $product->get_id() );
    }
    
    return $query_args;
}

方案二:自定义关联商品查询时直接排除

如果你是自己写了自定义函数来获取无子级子分类下的商品,那直接在WP_Query的参数里加上排除当前商品的条件就行:

假设你的自定义函数是这样的(根据你的实际逻辑调整):

function get_child_category_related_products( $current_product_id ) {
    $current_product = wc_get_product( $current_product_id );
    // 这里是你获取无子级子分类的逻辑,替换成你自己的代码
    $target_categories = get_no_child_product_categories( $current_product );
    
    $query_args = array(
        'post_type'      => 'product',
        'posts_per_page' => 4, // 按需调整显示数量
        'post__not_in'   => array( $current_product_id ), // 关键:排除当前商品
        'tax_query'      => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'term_id',
                'terms'    => wp_list_pluck( $target_categories, 'term_id' ),
            ),
        ),
    );
    
    $related_query = new WP_Query( $query_args );
    return $related_query->posts;
}

重点就是在$query_args里加上'post__not_in' => array( $current_product_id ),这样查询结果里就不会包含当前商品了。

内容的提问来源于stack exchange,提问作者Ace Chua

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:06:50