在 WooCommerce 中获取特定城市、州和邮政编码的送货区域

Get the shipping zone for specific city, state and postal code in WooCommerce

这就是我正在做的, 我在仪表板上添加了 3 个运输区域:

  1. 送货区1“2个城市”
  2. 配送区域 2“12 城市”
  3. 送货区 3 "rest of the world"

而且,我想在结帐页面显示与交付过程相关的特定消息,但我无法获取客户地址在哪个区域。

我做的是这样的:

/* get the order shipping zone meta data */

function get_shipping_zone(){

    global $woocommerce;
    $customer = new WC_Customer();
    $post_code = $woocommerce->customer->get_shipping_postcode();
    $zone_postcode = $woocommerce->customer->get_shipping_postcode();
    $zone_city =$woocommerce->customer->get_shipping_city(); 
    $zone_state = $woocommerce->customer->get_shipping_state(); 

    // for debugging 
    echo "<pre>";
    print_r($woocommerce->customer); 
    echo "</pre>"; 

    //show the customer order postal code, city
    echo "The post code is ". $post_code." <br/>"; 

    # here I should add the code to return the customer shipping zone ... ? 

}

我找到了这个功能,但它总是returns第三区我不知道为什么?

/* getting the shipping zone based on spesific package */

function get_shipping_zone( $package=Array()) {
    global $woocommerce;

    $shipping_zone = WC_Shipping_Zones::get_zone_matching_package($package);

    $zone=$shipping_zone->get_zone_name();

    return $zone;

} 

You should try WC()->session instead of WC()->customer. In WC()->session for protected 'shipping_for_package_0' data, you can access this data this way:

// Accessing to 'shipping_for_package_0' protected data
$shipping_package = WC()->session->get('shipping_for_package_0');

// Getting the instance of WC_Shipping_Rate object
foreach ($shipping_package['rates'] as $shipping_rate) break;

// Displaying accessing to the data in the object
echo 'Rate ID: ' . $shipping_rate->id . '<br>';
echo 'Rate Label: ' . $shipping_rate->label . '<br>';
echo 'Rate Cost: ' . $shipping_rate->cost . '<br>';
echo 'Rate Tax: ' . $shipping_rate->taxes[1] . '<br>';
echo 'Method ID: ' . $shipping_rate->method_id . '<br>';

还有:

$chosen_shipping_method = WC()->session->get('chosen_shipping_methods');

You can also use this code in a custom function hooked in this action hooks:

  • woocommerce_cart_totals_before_shipping (for cart)
  • woocommerce_review_order_before_shipping (for checkout)