【发布时间】:2018-02-05 15:55:26
【问题描述】:
因此,我试图找到一种解决方案,根据客户位置与卖家位置之间的距离向他们收费,但找不到合适的解决方案。我发现很少有插件可以完成类似的工作,例如使用 Google API 在仓库和发货地点之间收取不同的运费,但它们只处理一个特定的地点作为仓库。实际上,我有几个供应商在不同的位置设有仓库。
我正在使用 woocommerce 和 wc 供应商插件。
仅供参考...,我设置了一个元字段,使用 Google Api 收集供应商的纬度和经度。
//一个例子://
供应商 1 – 位置 1 供应商 2 – 位置 2
客户从供应商 1 下订单。客户的位置在 位置 A. API 将计算购物车项目之间的距离 供应商的位置,即位置 1,以及客户的位置,即 是位置 A。
Check the cart item's Vendor Get the location of Vendor If Location 1 to Location A = 3KM, Shipping Charge is 50; If Location 1 to Location A <= 5 KM, Shipping Charge is 100; Else Shipping Charge is 150;
//示例结束//
注意我只是找不到任何与 WC Vendor 插件配合得很好的远程运输费用插件。即使您设法给我任何可以完成这项工作的插件的链接,也将不胜感激。
所以,@loictheaztec 在下面提供了一个解决方案。我根据他的代码编写了一段代码。不幸的是,它对我不起作用。
add_filter( 'woocommerce_package_rates', 'distance_shipping_calculated_surcharge', 100, 2 );
function distance_shipping_calculated_surcharge( $rates, $package ) {
$shippingurl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=VENDOR_LOCATION&destinations=CUSTOMER_LOCATION&key=MY_API_KEY";
//fetch json response from googleapis.com:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $shippingurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
//If google responds with a status of OK
//Extract the distance text:
if($response['status'] == "OK"){
$dist = $response['rows'][0]['elements'][0]['distance']['text'];
}
// Get only number from string
$distance= filter_var ( $dist, FILTER_SANITIZE_NUMBER_INT);
// Distance example
//$distance = 3.5; //(in KM)
if( $distance > 5 )
$cost_operator = 3; // (3 * 50 = 150)
elseif( $distance > 3 && $distance <= 5 )
$cost_operator = 2; // (2 * 50 = 100)
else
$cost_operator = 1; // (1 * 50 = 50)
// Iterating through each shipping rate
foreach($rates as $rate_key => $rate_values){
$method_id = $rate_values->method_id;
$rate_id = $rate_values->id;
// Targeting "Flat Rate" shipping method
if ( 'flat_rate' === $rate_values->method_id ) {
// Set the new calculated rate cost
$rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cost_operator, 2);
// Taxes rate cost (if enabled)
foreach ($rates[$rate_id]->taxes as $key => $tax){
if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
$rates[$rate_id]->taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cost_operator, 2 );
}
}
}
}
return $rates;
}
【问题讨论】:
标签: php wordpress woocommerce google-api shipping