WooCommerce按配送/支付方式及邮编加额外费用的代码问题
WooCommerce结账页面额外费用代码问题排查与修复
原代码存在的核心问题
- 配送方式判断逻辑错误:原代码将格式为
flat_rate:8/free_shipping:9的配送方式字符串,直接与数组$shipping_method_id用===比较,字符串与数组永远不相等,导致条件始终不成立。 - 支付方式的场景限制:
woocommerce_cart_calculate_fees钩子会在购物车和结账页面同时触发,购物车阶段用户未选择支付方式,此时chosen_payment_method为空,直接导致条件不满足。 - 邮编获取的准确性不足:原代码调用用户账户默认账单邮编,未考虑结账时用户临时修改地址的情况,可能获取到非当前订单的邮编。
修正后的代码
add_action('woocommerce_cart_calculate_fees', 'add_extra_charge_for_specific_conditions'); function add_extra_charge_for_specific_conditions() { // 仅在结账表单页面执行,跳过购物车及订单完成等端点页面 if (is_checkout() && !is_wc_endpoint_url()) { // 定义触发额外费用的条件参数 $target_shipping_ids = array('8', '9'); // 对应flat_rate:8和free_shipping:9的ID部分 $payment_methods = array('cod', 'alphabank_gateway', 'bacs'); $target_zip_codes = array('49100', '29300', '10003'); // 获取选中的配送方式并校验 $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods'); if (empty($chosen_shipping_methods)) return; $chosen_shipping_method = $chosen_shipping_methods[0]; // 拆分配送方式字符串,提取ID部分 $shipping_id = end(explode(':', $chosen_shipping_method)); // 获取选中的支付方式并校验 $chosen_payment_method = WC()->session->get('chosen_payment_method'); if (empty($chosen_payment_method)) return; // 获取当前结账页面填写的邮编(优先账单邮编,兼容配送邮编) $customer_zip_code = WC()->checkout->get_value('billing_postcode'); if (empty($customer_zip_code)) { $customer_zip_code = WC()->checkout->get_value('shipping_postcode'); } // 所有条件满足时添加额外费用 if (in_array($shipping_id, $target_shipping_ids) && in_array($chosen_payment_method, $payment_methods) && in_array($customer_zip_code, $target_zip_codes)) { WC()->cart->add_fee(__('Geniki Taxydromiki 额外服务费', 'text-domain'), 5.00); } } }
关键修改说明
- 限定执行场景:通过
is_checkout() && !is_wc_endpoint_url()确保代码仅在结账表单页运行,避免购物车阶段的无效判断。 - 修复配送方式判断:拆分配送方式字符串提取ID,用
in_array判断是否符合目标列表。 - 优化邮编获取:直接读取结账页面当前填写的邮编,兼容账单和配送地址的情况。
- 增加空值校验:对配送方式、支付方式、邮编添加空值检查,避免变量为空导致的逻辑报错。
内容的提问来源于stack exchange,提问作者Sokratis Zervos
相关产品推荐
相关产品推荐

