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!
PHP Snippet 1: Force “Sold Individually” If Product Stock Is Low
/**
* @snippet Conditionally Force Sold Individually @ WooCommerce Cart
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire, BusinessBloomer.com
* @testedwith WooCommerce 4.5
* @donate $9 https://tutoraspire.com
*/
add_filter( 'woocommerce_is_sold_individually', 'tutoraspire_product_max_1_cart_stock_low', 9999, 2 );
function tutoraspire_product_max_1_cart_stock_low( $individually, $product ) {
if ( $product->get_stock_quantity()
PHP Snippet 2: Force “Sold Individually” If Product ACF Field Exists
/**
* @snippet Conditionally Force Sold Individually @ WooCommerce Cart
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire, BusinessBloomer.com
* @testedwith WooCommerce 4.5
* @donate $9 https://tutoraspire.com
*/
add_filter( 'woocommerce_is_sold_individually', 'tutoraspire_product_max_1_cart_custom_field', 9999, 2 );
function tutoraspire_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;
}