php - 根据特定产品有条件地删除 Woocommerce 购物车项目
问题描述
特定的 WooCommerce 产品只能单独在购物车中。
那么如何在将此特定产品添加到购物车时清除购物车?添加任何其他产品时,如何从购物车中删除此特定产品?
我已经知道如何在添加特定产品时清空购物车,但我不知道如何在添加任何其他产品时从购物车中删除该特定产品。
解决方案
以下将根据特定产品有条件地删除购物车项目:
- 将特定产品添加到购物车时,会删除所有其他项目。
- 当任何其他产品添加到购物车时,它会删除特定产品 (如果它在购物车中)
这是代码:
// Remove conditionally cart items based on a specific product (item)
add_action( 'woocommerce_before_calculate_totals', 'remove_cart_items_conditionally', 10, 1 );
function remove_cart_items_conditionally( $cart ) {
// HERE define your specific product ID
$specific_product_id = 37;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_items = $cart->get_cart(); // Cart items array
$items_count = count($cart_items); // Different cart items count
// Continue if cart has at least 2 different cart items
if ( $items_count < 2 )
return;
$last_item = end($cart_items); // Last cart item data array
$is_last_item = false; // Initializing
// Check if the specific product is the last added item
if ( in_array($specific_product_id, array( $last_item['product_id'], $last_item['variation_id'] ) ) ) {
$is_last_item = true;
}
// Loop through cart items
foreach ( $cart_items as $cart_item_key => $cart_item ) {
// Remove all others cart items when specific product ID is the last added to cart
if ( ! in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && $is_last_item ) {
$cart->remove_cart_item( $cart_item_key );
}
// Remove the specific item when its is not the last added to cart
elseif ( in_array($specific_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) && ! $is_last_item ) {
$cart->remove_cart_item( $cart_item_key );
}
}
}
代码继续在您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。
推荐阅读
- nginx - Google CDN 不缓存图像 - NGINX 问题或 CDN 设置?
- markdown - MarkDown(.md)文件中多行代码中的粗体文本?
- c# - Apple Pay web 使用 c#(在 ngrok 上测试)
- mysql - SQL 触发器问题:无法更新存储函数/触发器中的表,因为它已被调用此存储函数/触发器的语句使用
- python - Jupyter Lab 未执行 K 折交叉验证
- typescript - resolvejs 有什么好的现代打字稿示例吗?
- r - 在R中的两个条件下合并两列
- optimization - MT5ForConditionalGeneration 与 Pytorch-lightning 给出 attribute_error
- android - getStringExtra() 函数返回 Intent { (有额外) }
- tensorflow - 带有张量流的 ImportError