php - 在 WooCommerce 中根据 Variation 产品属性隐藏运输方式
问题描述
在 WooCommerce 中,我有两种运输方式和每个可变产品的两个产品属性值。客户应选择这些属性值之一将产品添加到购物车。
我正在尝试根据变体中选择的产品属性取消设置某些运输方式。例如,如果选择了产品属性“a”,则在购物车页面中仅应显示运输方式 1,如果选择了产品属性“b”,则应在购物车中显示运输方式 2。
我不知道我该怎么做。
解决方案
以下代码将隐藏基于产品变体产品属性术语定义的运输方式,定义为设置,在下面的代码中:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_variation_product_attribute', 10, 2 );
function hide_shipping_method_based_on_variation_product_attribute( $rates, $package ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE define the Product Attibute taxonomy (starts always with "pa_")
$taxonomy = 'pa_color'; // Example for "Color"
// HERE define shipping method rate ID to be removed from product attribute term(s) slug(s) (pairs) in this array
$data_array = array(
'flat_rate:12' => array('blue'),
'local_pickup:13' => array('black', 'white'),
);
// Loop through cart items
foreach( $package['contents'] as $cart_item ){
if( isset($cart_item['variation']['attribute_'.$taxonomy]) ) {
// The product attribute selected term slug
$term_slug = $cart_item['variation']['attribute_'.$taxonomy];
// Loop through our data array
foreach( $data_array as $rate_id => $term_slugs ) {
if( in_array($term_slug, $term_slugs) && isset($rates[$rate_id]) ) {
// We remove the shipping method corresponding to product attribute term as defined
unset($rates[$rate_id]);
}
}
}
}
return $rates;
}
代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。
刷新运输缓存 (必需):
- 此代码已保存在您的 function.php 文件中。
- 检查购物车是否为空……</li>
- 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。
你已经完成了,你可以测试它。
推荐阅读
- javascript - 带有可排序的工具提示给出了意想不到的结果
- jakarta-mail - javamail 抛出 javax.activation.UnsupportedDataTypeException: text/related; 字符集=UTF-8
- javascript - 选中的复选框不适用于扩展 chrome
- c# - 为什么我没有在 C# winForms 应用程序中获取 datagridview 可编辑列的最后一行的值?
- android - 从 shell 运行 react native android 应用程序时出错
- javascript - 从哈希数组中过滤重复的哈希 - Javascript
- python - 反转列表中的字符串并进一步反转嵌套列表中的列表
- python-3.x - 无法将 numpy dtypes 转换为其本机 python 类型(int64 到 int)
- git - Jenkins 检查是否在 Bitbucket 上创建了 Pull Request
- oracle - 日期未插入 oracle