我有一家在woocommerce中有多个供应商和客户的商店,我想根据不同城市添加不同的运费。例如,现在我有三个城市,所以我可以按条件处理运费,但是现在我需要再增加7个城市,以便如何使用条件处理
下面是我现在用来处理两个城市的代码,但是当我再添加7个城市时如何处理运输。
add_filter( 'woocommerce_package_rates', 'distance_shipping_calculated_surcharge', 100, 2 );
function distance_shipping_calculated_surcharge( $rates, $package ) {
global $woocommerce;
## HERE set your API code to get the distance ##
$items = $woocommerce->cart->get_cart();
$_product = array();
foreach($items as $item => $values) {
$_product[] = $values['data']->post;
// print_r($_product);
}
$product_in_cart_vendor_id = get_post_field( 'post_author', $_product[0]->ID);
//$product_added_vendor_id = get_post_field( 'post_author', $prodId );
//echo "product vendor id: ".$product_in_cart_vendor_id;
$vendor_detail = get_user_meta ($product_in_cart_vendor_id);
$vendor_city = ucfirst($vendor_detail ['_vendor_city'][0]);
// $user_id = get_current_user_id();
// $user_detail = get_user_meta($user_id);
//$user_city = $user_detail ['_billing_city'][0];
session_start();
//echo '<pre>' . print_r($_SESSION['city'], TRUE) . '</pre>';
if($_SESSION['city']){
$user_city = $_SESSION['city'];
//echo $user_city;
}
elseif(isset($_POST['billing_city'])){
$user_city = $_POST['billing_city'];
}
else{
$user_id = get_current_user_id();
$user_detail = get_user_meta($user_id);
$user_city = $user_detail ['billing_city'][0];
//echo $user_city;
}
// Distance example
//$distance = 2; //(in KM)
if( $vendor_city == 'A' && $user_city == 'B'){
$cost_operator = 50; // (3 * 50 = 150)
}
elseif( $vendor_city == 'B' && $user_city == 'A'){
$cost_operator = 50;
}
elseif( $vendor_city == 'B' || $vendor_city == 'A' && $user_city == ''){
$cost_operator = 30;
}
else{
$cost_operator = 30;
}
// Iterating through each shipping rate
foreach($rates as $rate_key => $rate_values){
$method_id = $rate_values->method_id;
$rate_id = $rate_values->id;
// if ( __( 'Local pickup', 'woocommerce' ) == $rate->label ){
// $rates[$rate_key]->label = __( 'Pick Up From Store', 'woocommerce' );
// }
//echo $rate_id;exit;
// Targeting "Flat Rate" shipping method
if ( 'flat_rate' === $rate_values->method_id ) {
// Set the new calculated rate cost
$rates[$rate_id]->cost = number_format($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($cost_operator, 2 );
}
}
}
}
return $rates;
session_destroy();
// print_r($rates);
// exit;
}
谢谢