2

I am trying to get the current shipping zone of the user but I am getting an error every time I am trying to get it

// The package. 

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

// Get the WC_Shipping_Zones instance object for the first package
$shipping_zone = $woocommerce->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>';

Error info

Error info

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

4

There are 2 issues:

  • $woocommerce global variable is not defined (and it's can be replaced by WC()),
  • wc_get_shipping_zone() is not a Woocommerce method but a function.

Try the following instead (for plugins see below):

// 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>';

It should work


For plugins, try

global $woocommerce;

// Get cart shipping packages
$shipping_packages = $woocommerce->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
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Your PHP code changes were rolled back due to an error on line 134 of file wp-content/plugins/risk-free-cash-on-delivery-cod-woocommerce/risk_free_advanced_cod.php. Please fix and try saving again. Uncaught Error: Call to undefined function WC() in wp-content/plugins/risk-free-cash-on-delivery-cod-woocommerce/risk_free_advanced_cod.php:134 Stack trace: #0 wp-settings.php(388): include_once() ... – Md Safiqul Islam Feb 03 '21 at 13:06
  • @Md.SafiqulIslam I have updated my answer… This seems to be an issue on an outdated plugin… – LoicTheAztec Feb 03 '21 at 13:10
  • Both of them are throwing errors. I also tried to downgrade the woo-commerce plugin . What should I check to fix the problem – Md Safiqul Islam Feb 03 '21 at 13:48
  • @Md.SafiqulIslam The problem seems to come from `risk-free-cash-on-delivery-cod-woocommerce` plugin that can't access Woocommerce global variable… It should load after woocommerce, checking that woocommerce is loaded before. Don't downngrade WooCommerce. – LoicTheAztec Feb 03 '21 at 14:25