1 回答
TA贡献1831条经验 获得超10个赞
假设您将修改woocommerce_package_rates过滤器,购物车中的所有商品都在key$package内的变量中contents,因此您可以简单地遍历它并提取所有 id 以检查您想要的产品是否在其中。
目的地信息也在键$package里面的变量中destination,它包含完整的送货地址,包括国家;
这是$package变量的json 输出示例
{
"contents": {
"044a23cadb567653eb51d4eb40acaa88": {
"key": "044a23cadb567653eb51d4eb40acaa88",
"product_id": 2754,
"variation_id": 0,
"variation": [],
"quantity": 2,
"data_hash": "b5c1d5ca8bae6d4896cf1807cdf763f0",
"line_tax_data": {
"subtotal": [],
"total": []
},
"line_subtotal": 35.9,
"line_subtotal_tax": 0,
"line_total": 35.9,
"line_tax": 0,
"data": {}
},
"0fc170ecbb8ff1afb2c6de48ea5343e7": {
"key": "0fc170ecbb8ff1afb2c6de48ea5343e7",
"product_id": 2800,
"variation_id": 0,
"variation": [],
"quantity": 1,
"data_hash": "b5c1d5ca8bae6d4896cf1807cdf763f0",
"line_tax_data": {
"subtotal": [],
"total": []
},
"line_subtotal": 107.95,
"line_subtotal_tax": 0,
"line_total": 107.95,
"line_tax": 0,
"data": {}
}
},
"contents_cost": 143.85,
"applied_coupons": [],
"user": {
"ID": 1
},
"destination": {
"country": "US",
"state": "",
"postcode": "",
"city": "Pine Bluff",
"address": "",
"address_1": "",
"address_2": ""
},
"cart_subtotal": 143.85,
"rates": {
"flat_rate:3": {}
}
}
所以有了这些信息,你可以做这样的事情来修改运输成本和运输标签
add_filter('woocommerce_package_rates', '_shipping_cost_product_ID', 100, 2);
function _shipping_cost_product_ID( $rates, $package ){
// duh
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// The ID of the product you want to modify shipping cost if found in cart
$discounted_product_id = 2800;
// Get all the product IDs added in cart and put them in array
$ids_in_cart = [];
foreach ( $package['contents'] as $key => $item ) {
$ids_in_cart[] = $item['product_id'];
}
// loop through each shipping rates
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
// Only modify shipping if all conditions below are meet
if(
'flat_rate' === $rate->method_id // if shipping method is "Flat RATE"
&& ( isset($package['destination']['country'] ) && $package['destination']['country'] == 'US' ) // if country is US
&& in_array($discounted_product_id, $ids_in_cart )//if $discounted_product_id is in cart
) {
$rates[$rate_key]->label = 'Cool Shipping'; // Modify Shipping Name
$rates[$rate_key]->cost = 3.00; // Modify Shiping Cost
//Taxes rate cost (if enabled)
$taxes = [];
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
$tax_rate = $initial_tax_cost / $initial_cost;
$taxes[$key] = $new_cost * $tax_rate;
$has_taxes = true;
}
}
if( $has_taxes ) $rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
- 1 回答
- 0 关注
- 179 浏览
添加回答
举报