我目前正在建立一个 WooCommerce 电子商店。我使用 Frequently Bought Together for WooCommerce 插件,以便客户能够以更优惠的价格在购物车中添加一包产品。
这是一个例子
这个概念是当客户购买“Husqvarna 325iLK”这个产品(或其他具有相同概念的产品)时,他可以以折扣价购买列出的配件。但折扣配件的数量不能超过母品数量。
所以我在 woocommerce_cart_item_quantity
中挂钩了一个函数
function change_quantity_input( $product_quantity, $cart_item_key, $cart_item ) {
// check if $cart_item has a parent_id
if (is_int( $cart_item["woobt_parent_id"])) {
// if yes I load the whole cart in order to check in which parent the product belongs
global $woocommerce;
$items = $woocommerce->cart->get_cart();
foreach ($items as $single_item ) {
// if the product has a parent I remove the quantity input and pass the quantity of the parent product
if($single_item['data']->get_id() == $cart_item["woobt_parent_id"]){
$child_q=$single_item['quantity'];
$woocommerce->cart->set_quantity($cart_item_key, $child_q);
}
}
$product_quantity=$child_q;
}
// return the child product quantity
return $product_quantity;
}
add_filter( 'woocommerce_cart_item_quantity', 'change_quantity_input', 10, 3);
所以我的购物车是这样的,当这个产品和一些配件被添加时
到目前为止一切顺利,一切正常。
当我将数量添加到父产品时,子产品的数量也会更新,但产品小计有问题
正如您在最后一张图片中看到的,每个产品的数量为 1。当我向父产品添加 +1 时,所有其他字段都会更新,但子产品小计显示之前的数量。虽然购物车小计计算正确。
让我用一些图片更好地解释它
在这张图片中,我在父数量上加了 1
如您所见,除了儿童产品的小计外,每个字段都已正确更新
即使是购物车的小计也是正确的。 ( 820 + 170 *2 + 150 *2 = 1460)
如果我再添加 1 到父级的产品数量,除了儿童产品的小计外,一切正常
购物车的小计再次正确!
所以我得出结论。每次更新父产品数量时,它都会计算产品的先前值。
我是否使用正确的钩子来实现我的目标?
有人知道为什么会这样吗?
任何帮助将不胜感激。
提前致谢
Vaggelis
附注。对不起,新蜜蜂代码:)