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
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