0
votes

I've been trying to create a simple shortcode function so I could display in the frontend of my website a list of available Shipping Zones along with their zone name, the country or state, the method title, and the shipping cost for each shipping zone.

I’m able to retrieve all the shipping zones names by making a simple loop with the help of WooCommerce get_zones() function, but it returns only the array of object.

The function:

function shipping_zones_shortcode() {

    $delivery_zones = WC_Shipping_Zones::get_zones();

    foreach ( (array) $delivery_zones as $key => $the_zone ) {
      echo ''.$the_zone['zone_name'].', ';

      print_r($delivery_zones);

    }
}

add_shortcode( 'list_shipping_zones', 'shipping_zones_shortcode', 10 );

Any help will be appreciated.

1

1 Answers

1
votes

The below sh;ould help you get on the right track. You just need to do some parseing of the object...

function shipping_zones_shortcode()
{

  $delivery_zones = WC_Shipping_Zones::get_zones();

  foreach ($delivery_zones as $key => $the_zone) {
    $my_zone = array(
      'name' => $the_zone['zone_name'],
      'location' => $the_zone['formatted_zone_location'],
      'methods' => array_map(function ($method) {
        return array(
          'title' => $method->method_title,
          'cost' => isset($method->cost) ? $method->cost : 0,
        );
      }, $the_zone['shipping_methods']),

    );

    print_r($my_zone);
  }
}

add_shortcode('list_shipping_zones', 'shipping_zones_shortcode', 10);

Output:

Array
  (
    [name] => United States (US)
    [location] => United States (US)
    [methods] => Array
  (
  [1] => Array
    (
      [title] => Free shipping
      [cost] => 0
    )
    [2] => Array
    (
      [title] => Flat rate
      [cost] => 90
    )
  )
)