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
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:
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:
get_shipping_packages is a method of WC_Cart. You can get the cart via
WC()->cart
, soshould return the shipping packages. https://www.businessbloomer.com/woocommerce-get-cart-info-total-items-etc-from-cart-object/