There are times when the WooCommerce product settings alone are not enough. You can already tick the “Sold individually” checkbox in the “Inventory” product data tab in the single product edit page to force quantity 1 for whatever product: “Enable this to only allow one of this item to be bought in a single order“.

Problem is, you may need to set this “programmatically” (via code), based on certain conditions. One reason is that you may not want to edit hundreds of products one by one (or in bulk) – another is that you may want to “override” whatever settings based on certain conditions (for example, you set “Sold Individually”, but if the Cart total is greater than 100 you want to allow quantities greater than 1).

As you can see, in this post we will cover, once again, the magic of “conditional logic“. Enjoy!

Yes, you can force max add to cart quantity to 1 via the product settings. But code is nicer and can be made dynamic or conditional.

PHP Snippet 1: Force “Sold Individually” If Product Stock Is Low

/**
 * @snippet       Conditionally Force Sold Individually @ WooCommerce Cart
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli, BusinessBloomer.com
 * @testedwith    WooCommerce 4.5
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_filter( 'woocommerce_is_sold_individually', 'bbloomer_product_max_1_cart_stock_low', 9999, 2 );

function bbloomer_product_max_1_cart_stock_low( $individually, $product ) {
	if ( $product->get_stock_quantity() < 3 ) {
		$individually = true;
	}
	return $individually;
}

PHP Snippet 2: Force “Sold Individually” If Product ACF Field Exists

/**
 * @snippet       Conditionally Force Sold Individually @ WooCommerce Cart
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli, BusinessBloomer.com
 * @testedwith    WooCommerce 4.5
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_filter( 'woocommerce_is_sold_individually', 'bbloomer_product_max_1_cart_custom_field', 9999, 2 );

function bbloomer_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;
}
Share:

Leave a Reply