gpt4 book ai didi

php - 当购物车商品具有特定运输类别时禁用运输方式?

转载 作者:行者123 更新时间:2023-12-05 03:08:14 25 4
gpt4 key购买 nike

如果购物车中有特定的送货类别,我会尝试禁用送货方式。我正在使用最新的 woocommerce 版本。

以下是我的任务代码。它位于主题的 functions.php 文件的末尾。

遗憾的是它不起作用。

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)并且有效:

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)

BUT you need (after saving your code to the function.php file of your active theme):

  1. To remove all cart items that are remaining in cart when testing.

  2. 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.

现在您可以再次测试,它应该可以工作了

关于php - 当购物车商品具有特定运输类别时禁用运输方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45598944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com