基本上,如果我有以下问题:
我们正在销售高度可定制的产品,这些产品的重量差异很大。我们正在以编程方式设置重量,然后添加到购物车。到目前为止,这非常有效。
但是,一旦访问者导航到结帐并更改他的邮政编码,这会触发运费计算的刷新,重量再次重置,这会导致错误的运费价格,因为我们使用基于重量的运费。
我们如何确保cart_item_data在设置一次后不会被刷新?
我们已经使用了this answer,以下是我的代码:
// This weight is taken from a custom plugin. The values retrieved are correct.
function changeWeight( $cart_item_data, $product_id, $variation_id ) {
$arrEzfc = $cart_item_data['ezfc_edit_values'];
$productWeight = 0;
foreach ( $arrEzfc as $key => $value ) {
//ID of 'Gesamtgewicht' values in calculating forms
if ( $key === 255 || $key === 280 || $key === 301 || $key === 330 || $key === 366 ) {
$productWeight = floatval( str_replace( ',', '.', str_replace( '.', '', $value ) ) );
$cart_item_data['weight']['new'] = $productWeight;
}
}
return $cart_item_data;
}
add_action( 'woocommerce_before_calculate_totals', 'conditionally_change_tax_class', 10000 );
function conditionally_change_tax_class( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Required since Woocommerce version 3.2 for cart items properties changes
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Looo through our specific cart item keys
foreach ( $cart->get_cart() as $cart_item ) {
// Set the new product weight
$cart_item['data']->set_weight($cart_item['weight']['new']);
}
}
字符串
2条答案
按热度按时间k5hmc34c1#
尝试以下简化和优化的代码版本(未经测试):
字符串
它可以工作。
6gpjuf902#
下面的代码解决了我们的问题:
字符串
基本上,每次结帐页面更新时,购物车物品的重量都会被重新设置。这样,就可以一直设置正确的重量。