Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save razorfrog/22fea73f41e9e571a2c11d6eabb474dc to your computer and use it in GitHub Desktop.
Save razorfrog/22fea73f41e9e571a2c11d6eabb474dc to your computer and use it in GitHub Desktop.
<?php
// Set minimum quantity per product before checking out
function razorfrog_set_min_qty_per_product() {
// Only run in the Cart or Checkout pages
if( is_cart() || is_checkout() ) {
// Product Id and Min. Quantities per Product
$product_min_qty = array(
20 => 100,
30 => 100,
40 => 100,
50 => 100,
);
// Will hold information about products that have not
// met the minimum order quantity
$bad_products = array();
// Loop through the products in the Cart
foreach( wc()->cart->cart_contents as $product_in_cart ) {
$product_id = $product_in_cart['product_id'];
// If there is a minimum quantity for the product and the cart item is below such quantity, add the cart item's product to the "bad" list
if( isset( $product_min_qty[$product_id] ) && ( $product_in_cart['quantity'] < $product_min_qty[$product_id] ) ) { $bad_products[] = array( 'id' => $product_id,
'in_cart' => $product_in_cart['quantity'],
'min_req' => $product_min_qty[$product_id],
);
}
}
// Time to build our error message to inform the customer about the minimum quantity per order.
if( !empty( $bad_products ) ) {
// 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']
.' lbs. You currently have: '. $bad_product['in_cart'] .'
';
}
wc_add_notice( $message, 'error' );
}
}
}
add_action( 'woocommerce_check_cart_items', 'razorfrog_set_min_qty_per_product' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment