How to set minimum quantity by code
-
How to set minimum quantity of a product by code
i try this but no luck
// Set minimum quantity per product before checking out
add_action( 'woocommerce_check_cart_items', 'spyr_set_min_qty_per_product' );
function spyr_set_min_qty_per_product() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
global $woocommerce;// Product Id and Min. Quantities per Product
$product_min_qty = array(
array( 'id' => 121, 'min' => 3 ),
);// Will increment
$i = 0;
// Will hold information about products that have not
// met the minimum order quantity
$bad_products = array();// Loop through the products in the Cart
foreach( $woocommerce->cart->cart_contents as $product_in_cart ) {
// Loop through our minimum order quantities per product
foreach( $product_min_qty as $product_to_test ) {
// If we can match the product ID to the ID set on the minimum required array
if( $product_to_test['id'] == $product_in_cart['product_id'] ) {
// If the quantity required is less than than the quantity in the cart now
if( $product_in_cart['quantity'] < $product_to_test['min'] ) {
// Get the product ID
$bad_products[$i]['id'] = $product_in_cart['product_id'];
// Get the Product quantity already in the cart for this product
$bad_products[$i]['in_cart'] = $product_in_cart['quantity'];
// Get the minimum required for this product
$bad_products[$i]['min_req'] = $product_to_test['min'];
}
}
}
// Increment $i
$i++;
}// Time to build our error message to inform the customer
// About the minimum quantity per order.
if( is_array( $bad_products) && count( $bad_products ) > 1 ) {
// Lets begin building our message
$message = 'A minimum quantity per product has not been met.
';
foreach( $bad_products as $bad_product ) {
// Append to the current message
$message .= get_the_title( $bad_product['id'] ) .' requires a minimum quantity of '
. $bad_product['min_req']
.'. You currently have: '. $bad_product['in_cart'] .'.
';
}
wc_add_notice( $message, 'error' );
}
}
}
- The topic ‘How to set minimum quantity by code’ is closed to new replies.