WooCommerce拆分发货场景下按订单ID获取商品对应配送信息
WooCommerce 订单商品关联配送方式实现方案
因为你是按商品配送分类(shipping_class)拆分的配送包裹,同一个配送分类下的商品会对应同一个配送方式,我们可以通过配送分类作为中间关联字段,把商品和对应的配送方式绑定,完整实现代码如下:
// 传入订单ID即可获取对应商品+配送的关联数据 function get_product_shipping_info_by_order( $order_id ) { $order = wc_get_order( $order_id ); if ( ! $order ) return []; $result = []; $shipping_map = []; // 存储【配送分类slug => 配送方式信息】的映射表 // 第一步:构建配送分类和配送方式的映射关系 foreach ( $order->get_items('shipping') as $shipping_item ) { // 你拆分包裹时直接用配送分类名称作为包裹名称,此处反查对应配送分类信息 $shipping_class_name = $shipping_item->get_name(); $shipping_class_term = get_term_by('name', $shipping_class_name, 'product_shipping_class'); if ( $shipping_class_term && !is_wp_error( $shipping_class_term ) ) { $shipping_map[ $shipping_class_term->slug ] = [ 'shipping_method_id' => $shipping_item->get_method_id(), 'shipping_method_name' => $shipping_item->get_name(), 'shipping_method_title' => $shipping_item->get_method_title() ]; } // 兼容无自定义配送分类的默认包裹场景 elseif ( str_starts_with( $shipping_class_name, 'Regular Shipping ' ) ) { $shipping_map[''] = [ 'shipping_method_id' => $shipping_item->get_method_id(), 'shipping_method_name' => $shipping_item->get_name(), 'shipping_method_title' => $shipping_item->get_method_title() ]; } } // 第二步:遍历订单商品,匹配对应配送信息 foreach ( $order->get_items() as $item ) { $product = $item->get_product(); if ( ! $product ) continue; $product_id = $item->get_product_id(); $shipping_class_id = $product->get_shipping_class_id(); $shipping_class_term = get_term( $shipping_class_id, 'product_shipping_class' ); $shipping_class_slug = $shipping_class_term->slug ?? ''; $shipping_class_name = $shipping_class_term->name ?? '默认配送分类'; $result[ $product_id ] = [ 'product_id' => $product_id, 'shipping_class_id' => $shipping_class_id, 'shipping_class_slug' => $shipping_class_slug, 'shipping_class_name' => $shipping_class_name, 'shipping_method' => $shipping_map[ $shipping_class_slug ] ?? [] ]; } return $result; } // thankyou.php 页面调用示例 $order_shipping_info = get_product_shipping_info_by_order( $order_id ); // 调试可输出查看结果:print_r($order_shipping_info);
核心关联逻辑是利用你自定义拆分包裹时的规则:配送包裹名称和商品配送分类名称一一对应,以此作为中间桥梁绑定商品和配送方式,不需要修改现有拆分发货的逻辑,兼容原有业务规则
补充说明
- 已经兼容无自定义配送分类的默认
Regular Shipping包裹场景 - 所有异常场景做了判空处理,不会抛出PHP警告
- 返回结果为数组格式,每个商品ID对应完整的配送类、配送方式信息,可直接输出到前端展示
内容的提问来源于stack exchange,提问作者Sapna Singh
相关产品推荐
相关产品推荐

