gpt4 book ai didi

php - 根据特定产品有条件地删除 Woocommerce 购物车项目

转载 作者:行者123 更新时间:2023-12-04 02:50:27 26 4
gpt4 key购买 nike

特定的 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 文件中。经过测试并有效。

关于php - 根据特定产品有条件地删除 Woocommerce 购物车项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55331789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com