Case:
In checkout packages are splited by shipping class of products (different brands). Every package have own shipping method that customer can choose.
And finally when customer make an order I need to store chosen shipping method for every product in meta_data so I can see it in order details on admin panel and for the RESTAPI (I use some external services to manage orders).
I tried something like this but I know this is mess, I don't understand how to handle session data and store it in order data.
add_action( 'woocommerce_checkout_create_order_shipping_item', 'order_shipping_item', 20, 4 );
function order_shipping_item($cartItemData,$order){
foreach ( WC()->cart->get_shipping_packages() as $package_id => $package ) {
// Check if a shipping for the current package exist
if ( WC()->session->__isset( 'shipping_for_package_'.$package_id ) ) {
// Loop through shipping rates for the current package
foreach ( WC()->session->get( 'shipping_for_package_'.$package_id )['rates'] as $shipping_rate_id => $shipping_rate ) {
$method_id = $shipping_rate->get_method_id(); // The shipping method slug
$instance_id = $shipping_rate->get_instance_id(); // The instance ID
$label_name = $shipping_rate->get_label(); // The label name of the method
}
}
foreach ($package['contents'] as $item) {
$item->add_meta_data('_shipping_method',$label_name);
# code...
}
}
}
Right now I have no idea how to achieve this, any clues? help!