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

时间:2019-03-25 05:39:13

标签: php wordpress woocommerce product cart

特定的WooCommerce产品只能自己放在购物车中。

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

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

2 个答案:

答案 0 :(得分:2)

以下内容将根据特定产品删除有条件的购物车商品:

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

代码如下:

// 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文件上。经过测试,可以正常工作。

答案 1 :(得分:0)

上面的方法很完美!移除物品后,您还可以在购物车中添加一条通知,以帮助改善用户体验。将其添加到第一个if语句中的 //遍历购物车项目部分:

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