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

Remove conditionally Woocommerce cart items based on a specific product

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

以上完美运行!您还可以在物品被移除后向购物车添加通知,以帮助改善用户体验。将此添加到第一个 if 语句中的 // 循环购物车商品 部分:

wc_add_notice( __( 'Product XYZ has been removed from your cart because...', 'theme_domain' ), 'notice' );