Restricting user to buy minimum quantity for products in woo-commerce is a pretty cool thing, we can achieve it by following the below steps
Step1:
1. Collect the product ids for which you wanted to restrict the quantity during checkout, store them in a array
<?php
$pd_min_quantity= array(
array( 'id' => 3587, 'min' => 99),
array( 'id' => 2554, 'min' => 87),
array( 'id' => 5587, 'min' => 52),
array( 'id' => 4488, 'min' => 40),
array( 'id' => 2555, 'min' => 80),
);
?>
Step2:
Add Following code to your themes - > functions.php
Note: don't forget to update your product ids and quantity
<?php
add_action( 'woocommerce_check_cart_items', 'restrict_product_quantity' );
function restrict_product_quantity() {
if( is_cart() || is_checkout() ) {
global $woocommerce;
$pd_min_quantity= array(
array( 'id' => 3587, 'min' => 99),
array( 'id' => 2554, 'min' => 87),
array( 'id' => 5587, 'min' => 52),
array( 'id' => 4488, 'min' => 40),
array( 'id' => 2555, 'min' => 80),
);
$i = 0;
$odd_prod = array();
foreach( $woocommerce->cart->cart_contents as $pd_cart ) {
foreach( $pd_min_quantity as $pd_quantity ) {
if( $pd_quantity['id'] == $pd_cart['product_id'] ) {
if( $pd_cart['quantity'] < $pd_quantity['min'] ) {
$odd_prod[$i]['id'] = $pd_cart['product_id'];
$odd_prod[$i]['in_cart'] = $pd_cart['quantity'];
$odd_prod[$i]['min_req'] = $pd_quantity['min'];
}
}
}
$i++;
}
if( is_array( $odd_prod) && count( $odd_prod ) > 1 ) {
$message = '<strong>Minimum quantity per product should be added.</strong><br />';
foreach( $odd_prod as $odd_prods ) {
$message .= get_the_title( $odd_prods['id'] ) .' requires a minimum quantity of '
. $odd_prods['min_req']
.'. You currently have: '. $odd_prods['in_cart'] .'.<br />';
}
wc_add_notice( $message, 'error' );
}
}
}
?>
Step3:
Done!!
No comments:
Post a Comment