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

如何在WooCommerce中应用自定义小计规则并影响购物车总金额

WooCommerce指定分类产品自定义购物车金额计算解决方案

问题原因

你原来使用的woocommerce_before_cart钩子仅适用于购物车页渲染前的前置操作,无法将计算后的价格写入购物车对象生效,应该使用WooCommerce专门用于修改购物车项价格的woocommerce_before_calculate_totals钩子实现需求。

可直接使用的实现代码

add_action( 'woocommerce_before_calculate_totals', 'custom_calculate_category_cart_price', 10, 1 );
function custom_calculate_category_cart_price( $cart ) {
    // 后台非AJAX操作跳过,避免影响后台订单编辑功能
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    // 定义需要特殊计算的产品分类别名
    $target_categories = ['circonscription'];
    
    // 遍历所有购物车项
    foreach ( $cart->get_cart() as $cart_item ) {
        // 判断当前产品是否属于目标分类
        if ( has_term( $target_categories, 'product_cat', $cart_item['product_id'] ) ) {
            // 沿用你原有计算逻辑
            $quantity = $cart_item['quantity'];
            $coefficient = ($quantity / 2) + 0.5;
            $original_price = $cart_item['data']->get_price();
            $custom_subtotal = round( $original_price * $coefficient );
            // 换算为单位价格写入产品对象,WooCommerce会自动计算行小计与总金额
            $cart_item['data']->set_price( $custom_subtotal / $quantity );
        }
    }
}

代码说明

  • 无需修改你原有分类判断、价格计算公式,直接替换现有代码即可生效
  • 新增后台操作跳过逻辑,避免干扰后台订单编辑功能
  • 计算完成后通过set_price()方法将价格写入产品对象,购物车、结算页、订单生成环节都会自动使用自定义计算的金额

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:45:04