WooCommerce自定义UPS配送方式在配送区域可见但结账页无选项问题咨询
修复方案
你的自定义UPS配送方式无法在结账页显示,核心问题是calculate_shipping方法调用add_rate时传入的参数不合法,WooCommerce不会渲染参数无效的配送方式,修复方案如下:
核心问题说明
WC_Shipping_Method类的add_rate方法要求传入包含至少id、label、cost三个字段的数组,你直接传入数值0属于无效参数,会导致配送方式被过滤- 你当前在
init方法中强制写死$this->enabled = 'yes'不影响当前显示,但会导致后台的启用/停用配置失效,可按需调整
修正后完整代码
add_action('woocommerce_shipping_init', 'UPS_number_shipping_method'); function UPS_number_shipping_method() { if (!class_exists('UPS_Number_Shipping_Method')) { class UPS_Number_Shipping_Method extends WC_Shipping_Method { public function __construct($instance_id = 0) { $this->id = 'UPS_number_shipping'; $this->instance_id = absint($instance_id); $this->domain = 'UPS_number_shipping'; $this->method_title = __('UPS Number', $this->domain); $this->method_description = __('Shipping method to be used when dealer has a UPS number', $this->domain); $this->title = __('UPS Number', $this->domain); $this->supports = array( 'shipping-zones', 'instance-settings', 'instance-settings-modal', ); $this->init(); } ## Load the settings API function init() { $this->init_form_fields(); $this->init_settings(); // 若需要支持后台配置启用状态,可替换为 $this->enabled = $this->get_option('enabled', 'yes'); $this->enabled = 'yes'; // 若需要支持后台配置配送方式名称,可替换为 $this->title = $this->get_option('title', __('UPS Number', $this->domain)); $this->title = __('UPS Number', $this->domain); add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options')); } public function calculate_shipping($packages = array()) { // 构造合法的配送费率参数 $rate = array( 'id' => $this->id, 'label' => $this->title, 'cost' => 0, // 可按需修改配送费用,当前设为0即免运费 'calc_tax' => 'per_order' // 计税规则可根据需求调整为per_item等 ); $this->add_rate($rate); } } } } add_filter('woocommerce_shipping_methods', 'add_UPS_number_shipping'); function add_UPS_number_shipping($methods) { $methods['UPS_number_shipping'] = 'UPS_Number_Shipping_Method'; return $methods; }
验证步骤
- 替换代码后清空WooCommerce缓存、站点缓存和浏览器缓存
- 进入后台配送区域设置,确认该配送方式已添加到对应配送区域,没有设置重量、金额等限制条件
- 前台加购商品后进入结账页,填写对应配送区域的收货地址即可看到该配送选项
如果修改后仍不显示,可排查是否有其他插件或主题的woocommerce_package_rates钩子过滤了可用配送方式。
内容的提问来源于stack exchange,提问作者coopersita
相关产品推荐
相关产品推荐

