How to Conditionally Force Product Quantity 1 at Cart in WooCommerce?

Sometimes, in WooCommerce, you wish to allow only one item to be bought in single order. You can enable this function easily by WooCommerce product settings. You just need to check in the “sold individually” checkbox. It is present under the “Inventory” data tab in the single product page. So, in this article, you will learn how to conditionally force product quantity 1 at cart. 

One cannot enable this setting for each single product. So, if you have products in bulk, then you need to code programmatically. Doing so, you can also alter in-built conditions as per your requirements. For instance, you may allow greater than 1 quantity if the total cart goes above 100. So, apply some coding and enjoy the results!

Image showing product settings that will be altered after applying conditionally force product quantity 1 at cart function

PHP Snippet 1: Conditionally Force Product Quantity 1 at Cart

add_filter( 'woocommerce_is_sold_individually', 'phpsof_product_max_1_cart_stock_low', 9999, 2 );
 
function phpsof_product_max_1_cart_stock_low( $individually, $product ) {
   if ( $product->get_stock_quantity() < 3 ) {
      $individually = true;
   }
   return $individually;
}

PHP Snippet 2: Conditionally Force “Sold Individually” if Product ACF Field exists

add_filter( 'woocommerce_is_sold_individually', 'phpsof_product_max_1_cart_custom_field', 9999, 2 );
 
function phpsof_product_max_1_cart_custom_field( $individually, $product ) {
   $acf_field_value = get_field( 'acf_field_id', $product->get_id() );
   if ( $acf_field_value && 'whatever' == $acf_field_value ) {
      $individually = true;
   }
   return $individually;
}

Where do you add this snippet?

So, this is how you can learn about conditionally force product quantity 1 at cart in WooCommerceAlso, it is easier to activate this function with this code. So, to apply this code, just add this PHP snippet at your child theme function.php file’s bottom. It should be placed before “?>”, if you have it there. Apart from this, CSS goes in your child theme style.css file. Make sure that you are editing these files in a right manner for best results.

Is this snippet still valid?

So, this is how you can learn about WooCommerce conditionally force product quantity 1 at cart. I have applied this code on the Storefront theme and WordPress friendly hosting PHP 7.3. Let me know if everything works as expected when you code. Share it further if you find this snippet useful for you and it had saved your time. 

Also Read, How to Add Shipping Phone at Checkout Page in WooCommerce?

How to Rename State Label at Checkout in WooCommerce?

Important links: WooCommerce – https://woocommerce.com/