6

How can I get the selected shipping zone ID based on the current user in WooCommerce?

I tried the code below, but I didn't get the zoneID from the cart page:

$bh_packages =  $cart->get_shipping_packages();
$shipping_zone = wc_get_shipping_zone( $bh_packages );
$zone = $shipping_zone->get_zone_name();  
var_dump($zone);
1
  • Any chance to get some feed back on the answer please (thank you). May 11, 2019 at 21:17

1 Answer 1

10

The problem is that WC_Cart get_shipping_packages() method gives an array of shipping packages and the function wc_get_shipping_zone( $package ) expect to have as argument a unique package.

So you need to get only one package, using for example php reset() function like:

// Get cart shipping packages
$shipping_packages =  WC()->cart->get_shipping_packages();

// Get the WC_Shipping_Zones instance object for the first package
$shipping_zone = wc_get_shipping_zone( reset( $shipping_packages ) );

$zone_id   = $shipping_zone->get_id(); // Get the zone ID
$zone_name = $shipping_zone->get_zone_name(); // Get the zone name

// Testing output
echo '<p>Zone id: ' . $zone_id . ' | Zone name: ' . $zone_name . '</p>';

Tested and works.

1
  • Thanks a bunch, I kept getting "Locations not covered by your other zones", turns out I just needed to pass one array key. Jul 4, 2021 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.