Search code examples
phpwordpresswoocommercepackageshipping-method

How to get custom shipping method packages from WooCommerce


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.


Solution

  • Because when using some 3rd Party shipping related plugins or some custom code, you can split the cart into multiple shipping packages, and so you can have multiple shipping methods (one per shipping package).

    Imagine that you sell products that can be heavy or not… Imagine that you allow shipping by plane, by boat and by truck… Some items will be shippable by plane some others will not depending on their weight.
    So when there are mixed items in cart (heavy and normal), the cart will be split into different shipping packages.

    So that's why there is an array of chosen shipping methods and an array of shipping packages (even if you don't split your cart or don't use those plugins).

    So there is only few WooCommerce shops that use multiple shipping packages, for mixed cart items.

    Related threads for shipping methods on WooCommerce orders: