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

基于配送地址关键词为WooCommerce订单添加配送附加费

针对特定地址(含多变体)的WooCommerce配送附加费解决方案

我们配送至6 Parramatta Square时,司机频繁遭遇延误问题,因此需要一套能根据配送地址文本/关键词自动添加附加费的系统,且要兼容客户输入的地址变体。由于该建筑订单量较大,我们整理了常见的地址变体,但没找到现成解决方案,于是自行开发了这套适配WooCommerce的代码,现分享给有需要的用户,也欢迎提出优化建议。

// 检查地址是否包含指定关键词
function check_complex_delivery_surcharge( $address1, $address2 ) {
    $keywords = array( '6PSQ', '6 PSQ', '6 Parramatta Sq', '10 Darcy' ); // 待匹配的地址关键词列表

    foreach ( $keywords as $keyword ) {
        // 不区分大小写检查地址是否包含关键词
        if ( stripos( $address1, $keyword ) !== false || stripos( $address2, $keyword ) !== false ) {
            return true;
        }
    }

    return false;
}

// 应用配送附加费
function apply_complex_delivery_surcharge() {
    $address1 = WC()->customer->get_shipping_address(); // 获取用户配送地址1
    $address2 = WC()->customer->get_shipping_address_2(); // 获取用户配送地址2
    
    if ( check_complex_delivery_surcharge( $address1, $address2 ) ) {
        // 添加12美元可征税的附加费,可修改名称和金额
        WC()->cart->add_fee( '复杂场地配送附加费', 12, true, '' );
        // 示例:WC()->cart->add_fee( '自定义附加费名称', 20, true, '' );
    }
}

// 挂钩到购物车费用计算环节,触发附加费逻辑
add_action( 'woocommerce_cart_calculate_fees', 'apply_complex_delivery_surcharge' );

// 添加附加费通知
function add_complex_delivery_notification() {
    $address1 = WC()->customer->get_shipping_address(); // 获取用户配送地址1
    $address2 = WC()->customer->get_shipping_address_2(); // 获取用户配送地址2
    
    if ( check_complex_delivery_surcharge( $address1, $address2 ) ) {
        echo '<tr class="complex-delivery-notice"><td colspan="2" style="color: #8B0000; font-size: x-small; padding: 5px; border: 1px solid black; text-align: left;">';
        echo '请注意:由于6 Parramatta Square建筑配送持续延误,该地址将收取<strong>复杂场地配送附加费</strong>,费用已添加至您的购物车(上方)。';
        echo '</td></tr>';
        // 可修改通知内容和样式,示例:echo '您的自定义通知内容';
    }
}

// 挂钩到订单总额后,显示附加费通知
add_action( 'woocommerce_review_order_after_order_total', 'add_complex_delivery_notification' );

// 移除重复通知
function remove_duplicate_notices() {
    wc_clear_notices(); // 清除已有的WooCommerce通知
}

// 挂钩到结账表单加载前,执行通知清除逻辑
add_action( 'woocommerce_before_checkout_form', 'remove_duplicate_notices', 1 );

可优化方向

  • 将关键词、附加费金额等配置项移至WooCommerce后台设置页面,无需修改代码即可更新规则
  • 增加地址预处理逻辑,比如去除多余空格、统一缩写格式(如把"Sq"统一为"Square"),提升匹配准确率
  • 支持多地址多费率配置,针对不同地址设置不同金额的附加费
  • 优化地址获取逻辑,避免在多个函数中重复调用WC()->customer->get_shipping_address()
  • 将通知样式从内联CSS移至主题样式表,便于统一管理和修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:27:20