skip to Main Content

I’m working on a WooCommerce plugin and I’m trying to fetch a list of all available shipping packages (this seems to be what they’re referred to as in WooCommerce). In other words I want all the shipping options which are potentially available to customers on checkout e.g. "First class", "Second class" and so on, rather than the shipping methods which just return "Flat rate", "Free shipping" etc.

Based on some research and similar code that I’m using to fetch shipping zones, methods etc, I tried using this code:

$shipping_packages = WC()->shipping()->get_shipping_packages();
foreach($shipping_packages as $shipping_package) {
   echo $shipping_package->label;
}

But it throws an error: PHP Fatal error: Uncaught Error: Call to undefined method WC_Shipping::get_shipping_packages()

Is there a method I can use to fetch the shipping packages?

2

Answers


  1. Chosen as BEST ANSWER

    I've worked this out now. For anyone trying to do the same thing, this is what I ended up doing. First I'm getting the shipping zones like this:

    $shipping_zones = WC_Shipping_Zones::get_zones();
    

    Then I'm iterating through the shipping methods from each zone, outputting the title with the zone name to differentiate between methods from each zone that may have the same title:

    foreach($shipping_zones as $shipping_zone) {
        $shipping_methods = $shipping_zone['shipping_methods'];
        foreach($shipping_methods as $shipping_method) {
            echo $shipping_method->title . ' (' . $shipping_zone['zone_name'] . ')';
        }
    }
    

  2. get_shipping_packages is a method of WC_Cart. You can get the cart via WC()->cart, so

    WC()->cart->get_shipping_packages()
    

    should return the shipping packages. https://www.businessbloomer.com/woocommerce-get-cart-info-total-items-etc-from-cart-object/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search