我在woocommerce运输选项中需要帮助,我想隐藏特定产品类别的统一费率,我只想显示本地送货或本地提货选项 .
对于所有其他类别,所有选项都应该有效
我已尝试使用该代码(在我的主题的function.php文件中添加):
function cart_has_product_with_orange_cats() {
global $woocommerce;
$product_in_cart = false;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
// second level loop search, in case some items have several categories
if($terms){
foreach ($terms as $term) {
$_categoryid = $term->term_id;
if ( $_categoryid == 16 ) {
//category is in cart!
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
// add filter and function to hide method
add_filter( 'woocommerce_available_shipping_methods', 'custom_shipping_methods' , 10, 1 );
function custom_shipping_methods( $available_methods ){
if ( cart_has_product_with_orange_cats() ) {
foreach($available_methods as $key => $method){
if( $key == 'local_delivery' || $key == 'local_pickup'){
continue;
}
unset($available_methods[$key]);
}
// remove the rate you want
}
// return the available methods without the one you unset.
return $available_methods;
}
但它不适合我,也许是因为最新的WooCommerce版本或任何其他问题的过时代码 .
我怎样才能做到这一点?
谢谢 .
1 回答
Update (与WC 3兼容,也适用于可变产品)
WooCommerce version 2.6+ 介绍 NEW shipping zones . 因此,与运费相关的所有WooCommerce先前版本的代码均为 outdated 和 will not work anymore .
我们不再需要您的自定义条件函数,因为WordPress中已存在一个条件函数,您可以将其作为WooCommerce产品类别的目标 . 此函数接受术语ID,术语slug或术语名称:
所以我们可以在这段代码中使用 has_term() 条件函数:
This code goes on function.php file of your active child theme or theme.
这段代码应该有效 if you have correctly set your shipping zones…
参考文献:
Hide other shipping methods when FREE SHIPPING is available
WooCommerce - Hide other shipping methods when FREE SHIPPING is available
WooCommerce 2.6 - Hiding paid shipping when free shipping is triggered by reaching specific amount
WooCommerce Cart - Conditional Items categories validation
How to Setup Shipping Zones in WooCommerce 2.6