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

WooCommerce购物车总额低于200时移除指定会员产品代码不生效求助

问题原因

  • 钩子选择错误且缺少刷新逻辑:当前使用的woocommerce_before_cart仅在购物车页面初始加载时触发,执行商品移除操作后没有触发页面重定向,页面展示的仍是删除前的缓存数据;woocommerce_checkout_process仅在结账提交时触发,不会提前在购物车交互场景下生效。
  • 钩子覆盖场景不全:缺少购物车内容更新(修改数量、加减商品)时的触发钩子,用户在购物车操作后总金额降到阈值以下时,你的移除逻辑不会自动运行。
  • 小逻辑瑕疵:判断指定产品时你硬编码了1111、1112两个ID,和前面定义的$product_ids变量重复,后续修改ID需要改两处容易出错。

修正后的代码

// 覆盖所有购物车更新、页面加载场景的钩子
add_action( 'woocommerce_before_cart', 'wc_minimum_order_amount' );
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
add_action( 'woocommerce_cart_updated', 'wc_minimum_order_amount' );
add_action( 'template_redirect', 'wc_minimum_order_amount' );
 
function wc_minimum_order_amount() {
    $minimum_amount = 200;
    $category_ids   = array( 83 ); 
    $product_ids    = array( 1111 , 1112 );
    $cart_updated = false; // 标记是否有商品被移除

    if( WC()->cart->is_empty() || ! ( is_cart() || is_checkout() ) ) 
        return; 

    $total_amount = WC()->cart->get_subtotal(); // 推荐用get_subtotal()方法兼容性更好

    if ( $total_amount < $minimum_amount ) {
        $needs_minimum_amount = false; 

        // 循环判断购物车是否存在需限制的商品/分类
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            $product_id   = $cart_item['product_id'];
            $variation_id = $cart_item['variation_id'];
            
            if( !empty($category_ids) ) {
                $taxonomy = 'product_cat';
                if ( has_term( $category_ids, $taxonomy, $product_id ) ) { 
                    $needs_minimum_amount = true;
                    break;
                }
            }

            if( !empty($product_ids) ) {
                if ( array_intersect( $product_ids, array($product_id, $variation_id) ) ) { 
                    $needs_minimum_amount = true;
                    break; 
                }
            }
        }

        if( $needs_minimum_amount ) {
            // 移除指定会员产品
            foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
                if ( in_array( $cart_item['product_id'], $product_ids ) ) {
                    WC()->cart->remove_cart_item( $cart_item_key );
                    $cart_updated = true;
                }
            }   
            
            // 商品移除后刷新页面,显示最新购物车状态
            if( $cart_updated && !is_checkout() && !wp_doing_ajax() ) {
                wp_redirect( wc_get_cart_url() );
                exit;
            }
            
            wc_print_notice( sprintf( 
                __("会员产品需订单满%s才可购买,当前订单总金额为%s。"), 
                wc_price( $minimum_amount ), 
                wc_price( $total_amount )
            ), 'error' );
        }
    }
}

额外注意事项

如果你的站点开启了购物车ajax更新功能,需要额外在ajax更新后触发页面刷新,或者将提示逻辑适配ajax场景,一般情况下上述代码已经可以覆盖绝大多数常规使用场景。

内容的提问来源于stack exchange,提问作者Site Lab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:09:04