在WooCommerce中的购物车页面上更新数量时拆分购物车项目 [英] Split cart items when quantity is updated on cart page in WooCommerce
问题描述
我想将同一产品的购物车项目拆分为单独的行.当我在单个产品页面上增加数量并添加到购物车时,它显示为单独的购物车项目.
我正在使用 WooCommerce-如果数量大于1,则将购物车物品分开对待.
我想在购物车页面上更新数量并单击更新购物车"时,则项目必须分成几行.
我该怎么做?
当购物车页面上的数量更新时,下面的代码将在单独的行上拆分项目.
注释,并在代码中添加了解释.
函数on_action_cart_updated($ cart_updated){如果($ cart_updated){//获取购物车$ cart_items = WC()-> cart-> get_cart();foreach($ cart_items as $ cart_item_key => $ cart_item){$ quantity = $ cart_item ['quantity'];//如果产品数量超过1if($ quantity> 1){//保留产品,但将其数量设置为1WC()->购物车-> set_quantity($ cart_item_key,1);//比总数量少运行1个循环对于($ j = 1; $ j< = $ quantity -1; $ j ++){//设置唯一键.$ cart_item ['unique_key'] = md5(microtime().rand().嗨妈妈!");//获取变量$ product_id = $ cart_item ['product_id'];$ variation_id = $ cart_item ['variation_id'];$ variation = $ cart_item ['variation'];//将产品添加为新的订单项,并传递相同的变体形式WC()->购物车-> add_to_cart($ product_id,1,$ variation_id,$ variation,$ cart_item);}}}}}add_action('woocommerce_update_cart_action_cart_updated','on_action_cart_updated',20,1);
I want to split cart items of same product in individual lines. When I increase quantity on single product page and add to cart, it shows as separate cart items.
Im using WooCommerce - Treat cart items separate if quantity is more than 1 answer code.
I want when quantity is updated on cart page and clicked on 'Update cart', then items must split on individual lines.
How can I do that?
The code below will split items on individual lines when quantity is updated on the cart page.
Comment with explanation added to the code.
function on_action_cart_updated( $cart_updated ) {
if ( $cart_updated ) {
// Get cart
$cart_items = WC()->cart->get_cart();
foreach ( $cart_items as $cart_item_key => $cart_item ) {
$quantity = $cart_item['quantity'];
// If product has more than 1 quantity
if ( $quantity > 1 ) {
// Keep the product but set its quantity to 1
WC()->cart->set_quantity( $cart_item_key, 1 );
// Run a loop 1 less than the total quantity
for ( $j = 1; $j <= $quantity -1; $j++ ) {
// Set a unique key.
$cart_item['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );
// Get vars
$product_id = $cart_item['product_id'];
$variation_id = $cart_item['variation_id'];
$variation = $cart_item['variation'];
// Add the product as a new line item with the same variations that were passed
WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item );
}
}
}
}
}
add_action( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );
这篇关于在WooCommerce中的购物车页面上更新数量时拆分购物车项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!