首页 > 解决方案 > 根据特定产品有条件地删除 Woocommerce 购物车项目

问题描述

特定的 WooCommerce 产品只能单独在购物车中。

那么如何在将此特定产品添加到购物车时清除购物车?添加任何其他产品时,如何从购物车中删除此特定产品?

我已经知道如何在添加特定产品时清空购物车,但我不知道如何在添加任何其他产品时从购物车中删除该特定产品。

标签: phpwordpresswoocommerceproductcart

解决方案


以下将根据特定产品有条件地删除购物车项目:

  • 将特定产品添加到购物车时,会删除所有其他项目。
  • 当任何其他产品添加到购物车时,它会删除特定产品 (如果它在购物车中)

这是代码:

// 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 文件中。测试和工作。


推荐阅读