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

如何修改WooCommerce PHP代码实现按品类添加固定金额附加费

修改WooCommerce指定品类附加费为固定金额版本

核心修改说明

原代码通过产品价格×购买数量×比例计算附加费,要改成固定金额收费,只需调整两个关键部分:

  • 把比例变量改为固定金额数值
  • 简化附加费计算逻辑,去掉产品价格的相乘

场景1:每购买1个指定品类商品,收取固定金额附加费

比如每个符合条件的商品单位收2元,买5个就收10元。修改后的代码如下:

function df_add_ticket_surcharge( $cart_object ) {
    global $woocommerce;
    $specialfeecat = 33; // 指定要收取附加费的品类ID
    $spfee = 0.00; // 初始化附加费总额
    $spfeeperunit = 2.00; // 每个商品单位的固定附加费金额(比如2元/个)

    foreach ( $cart_object->cart_contents as $key => $value ) {
        $proid = $value['product_id']; // 获取购物车中商品ID
        $quantity = $value['quantity']; // 获取商品购买数量
        $terms = get_the_terms( $proid, 'product_cat' ); // 获取商品所属品类

        if ( $terms && ! is_wp_error( $terms ) ) :
            foreach ( $terms as $term ) {
                $catid = $term->term_id;
                if($specialfeecat == $catid ) {
                    // 计算附加费:数量 × 单个固定金额
                    $spfee = $spfee + $quantity * $spfeeperunit;
                }
            }
        endif;  
    }

    if($spfee > 0 ) {
        // 添加附加费到购物车/结账页面,参数依次为:费用名称、金额、是否含税、税率类型
        $woocommerce->cart->add_fee( '票务服务费', $spfee, true, 'standard' );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge' );

场景2:每个指定品类的商品(无论购买数量),仅收取一次固定附加费

比如某商品买1个或10个,都只收5元固定费。修改后的代码如下:

function df_add_ticket_surcharge( $cart_object ) {
    global $woocommerce;
    $specialfeecat = 33; // 指定要收取附加费的品类ID
    $spfee = 0.00; // 初始化附加费总额
    $spfeeperitem = 5.00; // 每个符合品类的商品(SKU)固定附加费金额(比如5元/个SKU)
    $charged_items = array(); // 记录已收取过附加费的商品ID,避免重复收费

    foreach ( $cart_object->cart_contents as $key => $value ) {
        $proid = $value['product_id']; // 获取购物车中商品ID
        $terms = get_the_terms( $proid, 'product_cat' ); // 获取商品所属品类

        if ( $terms && ! is_wp_error( $terms ) && !in_array($proid, $charged_items) ) :
            foreach ( $terms as $term ) {
                $catid = $term->term_id;
                if($specialfeecat == $catid ) {
                    // 每个商品仅收取一次固定附加费
                    $spfee += $spfeeperitem;
                    $charged_items[] = $proid; // 标记该商品已收费
                    break; // 避免同一商品多品类重复触发
                }
            }
        endif;  
    }

    if($spfee > 0 ) {
        $woocommerce->cart->add_fee( '票务服务费', $spfee, true, 'standard' );
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'df_add_ticket_surcharge' );

关键自定义项

  1. 修改$specialfeecat的值为你需要的目标品类ID
  2. 修改$spfeeperunit/$spfeeperitem为实际要收取的固定金额
  3. 修改add_fee中的费用名称(比如“票务服务费”)为你需要的显示文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:20:22