wordpress 需要 Woocommerce 才能在购物车中只允许 1 个产品。如果一个产品已经在购物车中并且添加了另外 1 个产品,那么它应该删除之前的 1 个

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21363268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 19:27:55  来源:igfitidea点击:

Need Woocommerce to only allow 1 product in the cart. If a product is already in the cart and another 1 is added then it should remove the previous 1

wordpresswoocommerceproductcartshopping

提问by Swof

I think this code should work but not exactly sure where to place it. Everywhere I have tried has failed so far...

我认为这段代码应该可以工作,但不确定将它放在哪里。到目前为止,我尝试过的所有地方都失败了......

add_action('init', 'woocommerce_clear_cart');

function woocommerce_clear_cart() {
global $woocommerce, $post, $wpdb;

$url = explode('/', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$slug=$url[4];
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status='publish' AND post_name = '$slug'");

    if ($postid){
        if ($postid == PRODUCTID1 || $postid == PRODUCTID2){
        $woocommerce->cart->empty_cart();
        }
    }

}

回答by fornyhucker

Unfortunately there is no 'action' hook before WooCommerce adds an item to the cart. But they have a 'filter' hook before adding to cart. That is how I use it:

不幸的是,在 WooCommerce 将商品添加到购物车之前没有“动作”挂钩。但是他们在添加到购物车之前有一个“过滤器”挂钩。这就是我使用它的方式:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );

function woo_custom_add_to_cart( $cart_item_data ) {

    global $woocommerce;
    $woocommerce->cart->empty_cart();

    // Do nothing with the data and return
    return $cart_item_data;
}

回答by Jared

Based on the accepted answer and the latest Woo version 2.5.1 I updated the function to be slightly cleaner using the code woo uses in class-wc-checkout.php to clear the cart

基于接受的答案和最新的 Woo 版本 2.5.1,我使用 woo 在 class-wc-checkout.php 中使用的代码更新了该功能,使其更清晰,以清除购物车

add_filter( 'woocommerce_add_cart_item_data', '_empty_cart' );

    function _empty_cart( $cart_item_data ) {

        WC()->cart->empty_cart();

        return $cart_item_data;
    }

回答by helgatheviking

From my answer on another question:

从我对另一个问题的回答

There isa filter/hook that runs before an item is added to the cart as each product goes through validation before it is added.

存在一个过滤器/钩的项目之前的运行,因为每个产品经过验证被添加之前被添加到购物车。

So when validating a product, we can check if the item if there are already items in the cart and clears those (if the current item is able to be added) and adds an error message.

因此,在验证产品时,我们可以检查该商品是否已在购物车中,并清除这些商品(如果当前商品可以添加)并添加错误消息。

/**
 * When an item is added to the cart, remove other products
 */
function so_27030769_maybe_empty_cart( $valid, $product_id, $quantity ) {

    if( ! empty ( WC()->cart->get_cart() ) && $valid ){
        WC()->cart->empty_cart();
        wc_add_notice( 'Whoa hold up. You can only have 1 item in your cart', 'error' );
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'so_27030769_maybe_empty_cart', 10, 3 );

回答by Digamber

This worked like a charm for me, removes the previous product and adds the new one with the new product configuration. Cheers

这对我来说就像一个魅力,删除了以前的产品并添加了具有新产品配置的新产品。干杯

Update: For WooCommerce 3.0.X

更新:对于 WooCommerce 3.0.X

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

            if(!empty(WC()->cart->get_cart()) && $valid){
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];

                    if( $product_id == $_product->get_id() ) {
                        unset(WC()->cart->cart_contents[$cart_item_key]);
                    }
                }
            }

            return $valid;

        }
        add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );

For WooCommerce version less than 3.0.X

对于低于 3.0.X 的 WooCommerce 版本

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

    if(!empty(WC()->cart->get_cart()) && $valid){
        foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
            $_product = $values['data'];

            if( $product_id == $_product->id ) {
                unset(WC()->cart->cart_contents[$cart_item_key]);
            }
        }
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );

回答by Rebecca Dessonville

You have two options:

您有两个选择:

  1. WooCommerce Min/Max Quantities extension
  2. The following code added to your functions.phptheme file
  1. WooCommerce 最小/最大数量扩展
  2. 以下代码添加到您的functions.php主题文件中
    add_filter ( 'woocommerce_before_cart' , 'allow_single_quantity_in_cart' );
    function allow_single_quantity_in_cart() {
            global $woocommerce;

            $cart_contents  =  $woocommerce->cart->get_cart();
            $keys           =  array_keys ( $cart_contents );

            foreach ( $keys as $key ) {
                    $woocommerce->cart->set_quantity ( $key, 1, true );
            }
    }

回答by Ross

Don't add functions directly to your commerce files...you'll lose all your code when you update.

不要将函数直接添加到您的商业文件中……更新时您将丢失所有代码。

User functions should always be hooked through the functions.php of your theme.

用户函数应始终通过主题的functions.php 挂钩。

回答by Rao

Eu coloco na function.php do tema, o que fa?o ou no woocomerce

Eu coloco na function.php do tema, o que fa?o ou no woocomerce

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

    if(!empty(WC()->cart->get_cart()) && $valid){
        foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
            $_product = $values['data'];

            if( $product_id == $_product->id ) {
                wc_add_notice( 'The product is already in cart', 'error' );
                return false;
            }
        }
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );

回答by Jobin Jose

Try this,

尝试这个,

For removing the all products from the cart and adding the last added one,

要从购物车中删除所有产品并添加最后添加的产品,

//For removing all the items from the cart
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart($product_id,$qty);

class file is wp-content/plugins/woocommerce/classes/class-wc-cart.php.

类文件是wp-content/plugins/woocommerce/classes/class-wc-cart.php.

You can add the above code on the add to cart function in functions.php.

您可以在functions.php 中的添加到购物车功能中添加上述代码。

Hope its works..

希望它的作品..