Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save razorfrog/2bf3ca87390a7472f413d1549f9c5776 to your computer and use it in GitHub Desktop.
Save razorfrog/2bf3ca87390a7472f413d1549f9c5776 to your computer and use it in GitHub Desktop.
<?php
// 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' => 20, 'min' => 100 ),
array( 'id' => 30, 'min' => 100 ),
array( 'id' => 40, 'min' => 100 ),
array( 'id' => 50, 'min' => 100 ),
);
// 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 = '<strong>A minimum quantity per product has not been met.</strong>';
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' );
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment