php - 仅限英国和 Woocommerce 3 中的特定产品的定制免费送货
问题描述
我一直在尝试为客户的促销产品创建一个免费送货选项,该产品将在全球范围内发货,但只有来自英国的订单才有免费送货选项。因此,当有人从美国或香港订购时,将适用通常的费率。但不知何故,我不能将这些国家排除在航运类之外。(我没有使用免费送货方式,因为当我尝试时,它适用于所有产品,这就是我为此创建一个送货类的原因)
有人可以帮我弄这个吗?
非常感谢
解决方案
对于该特定情况,您无需在特定产品上使用运输方式。相反,下面的这个自定义函数可以解决问题,在其中定义您的特定产品 ID。
当来自英国的客户仅将您的特定产品添加到购物车时,代码会将您的统一运费方式重命名为“免费送货”,将成本设置为零。
要测试该代码,您应该首先在“运输选项”选项卡下的 Woocommerce 运输设置中启用调试模式。
此外,您还必须重新设置“统一费率”运输方式,或从您的特定产品中删除运输类别。
编码:
add_filter( 'woocommerce_package_rates', 'disable_shipping_methods', 20, 2 );
function disable_shipping_methods( $rates, $package ) {
// ==> HERE set your targeted product IDs in a coma separated array
$products_ids = array(37);
if( ! ( isset($package['destination']['country']) && isset($package['contents']) ) )
return $rates; // If 'destination' country is not defined, we exit
// Only for United kingdom customers
if( $package['destination']['country'] != 'GB' )
return $rates; // Non UK customers we exit.
// Loop through cart items and checking if there is any other products than the targeted ones
$found = false;
foreach( $package['contents'] as $item ) {
if( in_array( $item['data']->get_id(), $products_ids ) ){
$found = true;
} else {
return $rates; // Other items found in cart, we exit.
}
}
// When the customer is in UK and the target product is alone in cart we set the flat rate price to zero.
foreach ( $rates as $rate_key => $rate ){
// Targetting flat rate method
if( $rate->method_id == 'flat_rate' && $found ){
// We change the shipping label name
$rates[$rate_key]->label = __("Free shipping", "woocommerce");
// Set the rate cost to zero
$rates[$rate_key]->cost = 0;
// Taxes rate cost (if enabled)
$taxes = array();
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
$taxes[$key] = 0;
$has_taxes = true;
}
}
if( isset($has_taxes) && $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}
代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。
客户在购物车中使用此独特商品从英国购买 -免费送货
客户在英国将此商品和其他商品放入购物车 -正常运输
来自其他国家/地区的客户在购物车中有此独特商品 -正常运输
一旦你开始工作,不要忘记在“运输选项”选项卡下的 Woocommerce 运输设置中禁用调试模式。
推荐阅读
- java - 如何在java中同时运行线程并访问相同的资源
- c# - SIGABRT 抛出的 xamarin 在模型 c# 中形成自定义 getter/setter
- networking - 计算机可以在没有路由器的情况下向自己发送 UDP 数据报吗?
- php - 使用未定义的常量 SIGKILL - 假定为 'SIGKILL'
- python - CSV阅读器在python中将三列值作为单个字符串返回
- asp.net-core - .NET Core API LoggerFactory
- c# - 如何查询包含自定义字段的贷款?
- apache-spark - 如何避免 spark job 工作量偏差问题
- php - PHP新手:将输入框添加到数组
- javascript - jQuery outerHeight() 产生错误的 div 高度