根据特定产品有条件地删除Woocommerce购物车项目 [英] Remove conditionally Woocommerce cart items based on a specific product

查看:52
本文介绍了根据特定产品有条件地删除Woocommerce购物车项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

A specific WooCommerce product can only be by itself in the cart.

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

So how do I clear the cart while adding this specific product to the cart? and how can I remove this specific product from the cart when adding any other product?

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

I've figured out how to empty the cart when adding a specific product but I don't know how to remove this specific product from the cart when adding any other product.

推荐答案

以下内容将有条件地删除购物车中的商品基于特定产品:

The following will remove conditionally cart items based on a specific product:


  • 将特定产品添加到购物车后,所有其他项目都将被删除。

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

  • When the specific product is added to cart, all other items are removed.
  • When any other product is added to cart, it removes the specific product (if it's in cart)

这是代码:

// 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上执行代码活动子主题(或活动主题)的文件。经过测试,可以正常工作。

Code goes on function.php file of your active child theme (or active theme). Tested and works.

这篇关于根据特定产品有条件地删除Woocommerce购物车项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆