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

如何将WooCommerce中不同的C.R.V.合并为单一费用项?

解决WooCommerce中C.R.V.费用合并显示的问题

你的问题出在原代码会为每个不同金额区间的C.R.V.单独添加费用条目,所以购物车会显示多条记录。要合并成单一条目,只需要计算所有商品的C.R.V.总金额,再一次性添加统一名称的费用即可。

修改后的代码如下:

function action_woocommerce_cart_calculate_fees( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // 初始化C.R.V.总金额
    $total_crv = 0;

    // 设置:商品ID组对应C.R.V.金额
    $crv_settings = array(
        array(
            'product_ids' => array( 11891, 11893 ),
            'amount'      => 0.05,
        ),
        array(
            'product_ids' => array( 11892 ),
            'amount'      => 0.10,
        ),
        array(
            'product_ids' => array( 825 ),
            'amount'      => 0.20,
        ),
    );
    
    // 遍历购物车商品
    foreach ( $cart->get_cart_contents() as $cart_item ) {      
        $product_id = $cart_item['product_id'];
        $quantity = $cart_item['quantity'];
        
        // 匹配对应商品的C.R.V.金额并累加
        foreach ( $crv_settings as $setting ) {
            if ( in_array( $product_id, $setting['product_ids'] ) ) {
                $total_crv += $setting['amount'] * $quantity;
                break; // 找到匹配项后跳出循环,避免重复计算
            }
        }       
    }
    
    // 如果总金额大于0,添加统一的C.R.V.费用条目
    if ( $total_crv > 0 ) {
        $cart->add_fee( __( 'C.R.V.', 'woocommerce' ), $total_crv, false );    
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );

关键修改说明:

  • 新增$total_crv变量,专门用来累计所有商品的C.R.V.总费用
  • 简化了设置数组,去掉了原有的name和total_amount字段,只保留必要的商品ID组和对应金额
  • 遍历购物车商品时,找到匹配的C.R.V.金额就直接累加到总金额里,并用break避免同一商品被多次匹配
  • 最后只在总金额大于0时,添加一条名为“C.R.V.”的费用条目,确保购物车只显示一行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:16:07