问题描述
如果购物车中有特定的运输类别,我会尝试禁用一种运输方式。我正在使用最新的woocommerce版本。
I try to disable a shipping method if a specific shipping class is in the cart. Im using the newest woocommerce version.
下面是我执行任务的代码。
它放在主题的 functions.php
文件的末尾。
Below is my Code for my task.Its placed at the end of my functions.php
file of my Theme.
不幸的是,它不是
add_filter( 'woocommerce_package_rates', 'businessbloomer_hide_free_shipping_for_shipping_class', 10, 2 );
function businessbloomer_hide_free_shipping_for_shipping_class( $rates, $package ) {
$shipping_class_target = 513; // ID OF MY SHIPPING_CLASS
$in_cart = false;
foreach( WC()->cart->cart_contents as $key => $values ) {
if( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
$in_cart = true;
break;
}
}
if( $in_cart ) {
unset( $rates['flat_rate:2'] ); //VALUE:ID OF MY SHIPPING METHOD
}
return $rates;
}
推荐答案
我已经测试了一些简化您的代码(带有我的WC设置的ID),并且有效:
I have tested simplifying a little your code (with the ids of my WC settings) and it works:
add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 10, 2 );
function custom_hide_shipping_methods( $rates, $package ) {
foreach( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item[ 'data' ]; // The WC_Product object
$shipping_class_id = $product->get_shipping_class_id();
if( isset($rates['flat_rate:2']) && $shipping_class_id == 513 ) { // <== ID OF MY SHIPPING_CLASS
unset( $rates['flat_rate:2'] ); // Removing specific shipping method
break; // we stop the loop
}
}
return $rates;
}
所以您的代码也应该工作 (如果您有设置正确的ID)
-
要删除购物车中剩余的所有购物车商品测试。
刷新发货缓存:
为此,您可以进入运输区域并禁用一个统一费率 (例如)和保存。然后,重新启用该统一费率和保存。您完成了。
To refresh the shipping caches:
To do it, you can go in a shipping zone and disable one "flat rate" (for example) and "save". Then re-enable that "flat rate" and "save". You are done.
现在您可以再次测试了,应该工作
这篇关于当购物车商品具有特定的运输类别时,禁用运输方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!