在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文件中。测试并起作用。
刷新运输caches (必需):
- 此代码已经保存在您的function.php文件上。
- 检查购物车是否为空…
- 在运输区设置中,禁用/保存任何运输方法,然后启用返回/保存。
您完成了,您可以对其进行测试。