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
Asked Answered
J

10

22

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();
        }
    }

}
Jeopardy answered 26/1, 2014 at 12:23 Comment(0)
C
48

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:

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;
}
Coralline answered 25/3, 2014 at 11:2 Comment(3)
Worked perfectly for me. I also set the option to limit the item's quantity to only one per order.Kakalina
Worked perfectly for me as well +1Uncloak
How can we modify this so that we can also limit the qty to just 1 as well?Qktp
N
15

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

add_filter( 'woocommerce_add_cart_item_data', '_empty_cart' );

    function _empty_cart( $cart_item_data ) {

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

        return $cart_item_data;
    }
Nonprofit answered 28/1, 2016 at 14:53 Comment(0)
K
12

There is a 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 );
Kist answered 20/11, 2014 at 11:56 Comment(0)
N
9

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

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

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 );
Nonmetal answered 3/6, 2015 at 4:20 Comment(2)
Worked perfectly for me—I had converted the product quantity selector to my own values in a dropdown so needed to limit how many the user added. This allows only one row of a single line of product.Billyebilobate
@Gauchocode have updated the answer to work with WooCommerce 3.0.XNonmetal
T
4

You have two options:

  1. WooCommerce Min/Max Quantities extension
  2. The following code added to your functions.php theme file

    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 );
            }
    }

Teryl answered 5/8, 2014 at 5:56 Comment(0)
S
3

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.

Satisfactory answered 27/1, 2014 at 23:29 Comment(0)
C
3

Add this to your child-themes functions.php (tested in 2022, requires PHP 7 or higher):

add_filter('woocommerce_add_cart_item_data', function($cart_data) {
    wc_empty_cart();
    return $cart_data;
}, 99);

The "woocommerce_add_cart_item_data" filter fires every time a new item is added to the cart. We use this chance to call "wc_empty_cart" which empties the cart and optionally the persistent cart too. The new items is therefore alone in the cart.

Click answered 1/5, 2022 at 18:0 Comment(1)
This is awesome! +1 for this superb solution!Remaremain
C
2

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.

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

Hope its works..

Calycle answered 27/1, 2014 at 6:11 Comment(0)
S
2

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 );
Stretcher answered 18/3, 2015 at 9:29 Comment(0)
R
2

Wordpress Product Update Process

On WordPress 5.6.1. no need to add a custom filter or write code there is an option to limit one product add to the cart.

Recuperate answered 6/2, 2021 at 1:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.