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

WooCommerce修改配送方式标签显示费用:移除补贴金额

问题描述

我在WooCommerce中配置了基于配送方式的补贴,目前配送公司的原费用与扣除补贴后的新费用会同时显示。我希望仅在配送方式标签中展示扣除补贴后的费用,尝试了以下代码但未达到预期效果,请问如何修改配送方式的显示费用?

/*---- Remove subsidy from displayed shipping cost -----*/
add_filter( 'woocommerce_cart_shipping_method_full_label', 'costo_del_metodo_menos_subscidio', 10, 2 );
function costo_del_metodo_menos_subscidio( $label, $method ) {
    // If shipping method cost is 0 or null, display 'Free' (except for free shipping method)
     $cost=$method->cost;   
     $subsidy = get_total_subsidies( WC()->cart->get_cart() );
    if (  ( ($cost-$subsidy) < 0 ) && $method->method_id !== 'local_pickup' ) {
        $label .= ': ' .' <span class="shipping_method gratis">' . __('¡Gratis!').'</span>';
    }
    else
    if (  ( ($cost-$subsidy) > 0 ) && $method->method_id !== 'local_pickup' ) {
        $label .= ': ' .' <span class="shipping_method gratis">' . wc_price($cost-$subsidy).'</span>';
    }
    return  $label;
}
解决方案

你的代码问题在于直接把补贴后的费用追加到了原有标签后面,导致原费用和新费用同时显示。正确做法是替换掉标签中原有的费用部分,而不是叠加。以下是修改后的代码:

/*---- 仅显示扣除补贴后的配送费用 -----*/
add_filter( 'woocommerce_cart_shipping_method_full_label', 'display_shipping_cost_after_subsidy', 20, 2 );
function display_shipping_cost_after_subsidy( $label, $method ) {
    // 跳过自提方式,保持原有显示逻辑
    if ( $method->method_id === 'local_pickup' ) {
        return $label;
    }

    $original_cost = $method->cost;
    $subsidy = get_total_subsidies( WC()->cart->get_cart() );
    $final_cost = max( 0, $original_cost - $subsidy ); // 确保费用不会出现负数

    // 提取纯配送方式名称(剔除原有费用部分)
    $method_name = preg_replace( '/:\s*(\d+(\.\d+)?\s*[^\s]+)?$/', '', $label );

    // 根据最终费用生成显示文本
    if ( $final_cost === 0 ) {
        $cost_text = '<span class="shipping_method gratis">' . __('免费!') . '</span>';
    } else {
        $cost_text = '<span class="shipping_method">' . wc_price( $final_cost ) . '</span>';
    }

    // 重新组合标签:配送名称 + 补贴后费用
    return $method_name . ': ' . $cost_text;
}

关键修改点

  1. 替换逻辑:用正则表达式去掉原有标签里的费用内容,只保留配送方式名称,再重新拼接补贴后的费用,避免双费用显示。
  2. 优先级调整:把过滤器优先级从10改为20,确保在WooCommerce默认显示逻辑之后执行,避免被覆盖。
  3. 异常处理:用max(0, ...)保证最终费用不会为负数,避免显示异常。
  4. 逻辑简化:合并条件判断,覆盖了费用为0的场景,代码更清晰。

注意:如果你的补贴是按配送方式单独设置的,需要调整get_total_subsidies函数,传入当前$method参数来获取对应配送方式的补贴,而不是统一取购物车总补贴。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:07:08