2

In my custom Woocommerce template I want to restrict the quantity of a product to 1.

I'm working from Empty cart upon page load allowing add to cart in WooCommerce answer to my previous question.

This is what I have:

 <?php 
$current_product_id = 5; // The product ID 
$cart               = WC()->cart; // The WC_Cart Object
       $quantity = $cart_item['quantity'];//the quantity
// When cart is not empty 
if ( ! $cart->is_empty() ) {
    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // If the cart item is not the current defined product ID
        if( $current_product_id != $cart_item['product_id'] ) {
            $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        }
}
 if( $quantity >=1) {
    $cart->remove_cart_item( $cart_item_key ); // remove it from cart
 } }}
?>

It kind'a works. But I want checkout on the same page, and with this code checkout does not update when product is added to cart.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
tiny
  • 447
  • 4
  • 18
  • 2
    Without really reading your question or code thoroughly. Is it not an option to check 'Activate this if this item can only be purchased once per order' in the product inventory options? – 7uc1f3r Jul 08 '20 at 21:22
  • That would work. – tiny Jul 08 '20 at 21:52

2 Answers2

2

To restrict the quantity to 1 you will use the WC_cart set_quantity() method this way:

<?php 
$current_product_id = 5; // The product ID 
$cart               = WC()->cart; // The WC_Cart Object

// When cart is not empty 
if ( ! $cart->is_empty() ) {
    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // If the cart item is not the current defined product ID
        if( $current_product_id != $cart_item['product_id'] ) {
            $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        } 
        // If the cart item is the current defined product ID and quantity is more than 1
        elseif( $cart_item['quantity'] > 1 ) {
            $cart->set_quantity( $cart_item_key, 1 ); // Set the quantity to 1
        }
    }
}
?>

It should work.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
0

For anyone who is looking to achieve the same functionality without code. You can simply select Sold Individually checkbox in the inventory settings of the product(Check the attached Image) You can also achieve this with code like this: update_post_meta($product_id, '_sold_individually', 'yes');