I wrote custom shipping method according to WooCommerce Shipping Method API documentation. It works fine and is doing what I need when calculating price on cart and checkout page. Also I have validation function on checkout page and and I'm getting packages, then comparing it to chosen methods.
The code goes following way:
$packages = WC()->shipping->get_packages();
$chosen_methods = wc_get_chosen_shipping_method_ids();
if (is_array($chosen_methods) && (in_array('new_standard', $chosen_methods) || in_array('new_fast', $chosen_methods) || in_array('new_express', $chosen_methods))) {
foreach ($packages as $i => $package) {
if ($chosen_methods[$i] != 'new_standard' && $chosen_methods[$i] != 'new_fast' && $chosen_methods[$i] != 'new_express') {
continue;
}
// Here some validation code
if ($package['destination']['city'] == 'Paris') {
// Bla bla bla
}
}
}
Can you help me to understand why do I need to have multiple packages for single order. Why I'm getting array for shipping methods wc_get_chosen_shipping_method_ids()
instead of getting one id of method. Why I'm using foreach loops to get there, when it can be more straight forward like this:
// This is just example code of mine for showcase
$package = WC()->shipping->get_package();
if ($package['id'] == 'new_standard' || $package['id'] == 'new_fast' || $package['id'] == 'new_express') {
// validation code here
}
Also the main question is: How can I get packages and use them with WC_Order. I need to call some external API and for this I need to do same thing what is described above.