我对此代码片段有问题.我使用的是最新版本的WooCommerce(8.6.1).
我正在努力实现以下目标:
在 checkout 期间,当客户在特定的发货区(ID 29),并且购物车中至少有2个产品具有特定的发货类别(ID 343)时,我希望他们的发货类别更改为另一个(ID 344).然而,下面的代码似乎没有做任何事情.这可能是什么问题?
// Custom function to change shipping class if conditions are met
function adjust_shipping_class_based_on_quantity() {
// Get the current cart contents
$cart = WC()->cart->get_cart();
// Check if the cart contains items and the first item has a destination
if ( ! empty( $cart ) && isset( $cart[0]['destination'] ) && is_array( $cart[0]['destination'] ) ) {
// Get the shipping zone ID
$zone_id = WC_Shipping_Zones::get_zone_matching_package( array( 'contents' => $cart ) )->get_id();
// Check if the shipping zone ID is 29
if ( $zone_id == 29 ) {
// Initialize variables to count 'Letter box' items
$letter_box_count = 0;
// Loop through cart items to count 'Letter box' items
foreach( $cart as $item ) {
if ( isset( $item['data'] ) && $item['data']->get_shipping_class_id() == 343 ) {
// Increment count for each 'Letter box' item
$letter_box_count += $item['quantity'];
}
}
// If there are at least 2 'Letter box' items, change shipping class of all 'Letter box' items to 344
if ( $letter_box_count >= 2 ) {
// Loop through cart items again to change shipping class if shipping class ID is 343
foreach( $cart as $key => $item ) {
if ( isset( $item['data'] ) && $item['data']->get_shipping_class_id() == 343 ) {
// Change the shipping class of the item to 'regular-package'
$cart[$key]['data']->set_shipping_class_id(344);
}
}
}
// Set the modified cart contents
WC()->cart->set_cart( $cart );
}
}
}
add_action( 'woocommerce_cart_loaded_from_session', 'adjust_shipping_class_based_on_quantity' );
我将上面的代码片断添加到了函数.php文件中,并添加到了FluentSnipets插件中.都没有给我带来想要的结果.我还判断了以下不兼容性,这似乎不是问题:
- 插件不兼容
- 与其他代码片段不兼容
- 主题不兼容