在woocommerce的购物车页面上拆分产品数量到新行



我使用以下代码将数量大于1 in的产品分割为单独的行。

但是,如果我添加5个相同的产品,它会延迟,需要很长时间,并且经常给出502坏网关错误,因为ajax正在循环遍历每个产品的代码。

我想知道,如果不是在添加到购物车上运行这个功能,我可以复制这个功能,当用户实际进入购物车页面时,这样ajax购物车就不会显示每个产品,它只会显示例如product A - 100

而不是显示100个。我只想在购物车页面的一行上显示100个,每个1个。

这是我当前使用的代码

add_action( 'woocommerce_add_to_cart', 
'mai_split_multiple_quantity_products_to_separate_cart_items', 10, 6 );

function mai_split_multiple_quantity_products_to_separate_cart_items( 
$cart_item_key, $product_id, $quantity, 
$variation_id, $variation, $cart_item_data ) 
{
// 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 ( $i = 1; $i <= $quantity -1; $i++ ) {
/**
* Set a unique key.
* This is what actually forces the product into its own cart line item
*/
$cart_item_data['unique_key'] = md5( microtime() . rand() . "Hi Mom" );
// 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_data );
}
}
}

你在一个无尽的循环中。WC()->cart->add_to_cart方法触发函数附加到的'woocommerce_add_to_cart'动作钩子。

您可以在这里找到一些详细信息:https://woocommerce.wp-a2z.org/oik_hook/woocommerce_add_to_cart/

快速修复方法是用一个额外的检查扩展if语句:

if ( !isset($cart_item_data['unique_key']) && $quantity > 1 ) {
... 
}