Skip to content

Instantly share code, notes, and snippets.

@kartikparmar
Last active July 23, 2021 09:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kartikparmar/bf6381ce3969497f9ab1a32880f299c2 to your computer and use it in GitHub Desktop.
Save kartikparmar/bf6381ce3969497f9ab1a32880f299c2 to your computer and use it in GitHub Desktop.
Validation on the Update Cart button on Cart page
<? php
/*
* Get the total quantity of the product available in the cart.
*/
function wc_qty_get_cart_qty( $product_id , $cart_item_key = '' ) {
global $woocommerce;
$running_qty = 0; // iniializing quantity to 0
// search the cart for the product in and calculate quantity.
foreach($woocommerce->cart->get_cart() as $other_cart_item_keys => $values ) {
if ( $product_id == $values['product_id'] ) {
if ( $cart_item_key == $other_cart_item_keys ) {
continue;
}
$running_qty += (int) $values['quantity'];
}
}
return $running_qty;
}
/*
* Validate product quantity when cart is UPDATED
*/
function wc_qty_update_cart_validation( $passed, $cart_item_key, $values, $quantity ) {
$product_min = wc_get_product_min_limit( $values['product_id'] );
$product_max = wc_get_product_max_limit( $values['product_id'] );
if ( ! empty( $product_min ) ) {
// min is empty
if ( false !== $product_min ) {
$new_min = $product_min;
} else {
// neither max is set, so get out
return $passed;
}
}
if ( ! empty( $product_max ) ) {
// min is empty
if ( false !== $product_max ) {
$new_max = $product_max;
} else {
// neither max is set, so get out
return $passed;
}
}
$product = wc_get_product( $values['product_id'] );
$already_in_cart = wc_qty_get_cart_qty( $values['product_id'], $cart_item_key );
if ( isset( $new_max) && ( $already_in_cart + $quantity ) > $new_max ) {
wc_add_notice( apply_filters( 'wc_qty_error_message', sprintf( __( 'You can add a maximum of %1$s %2$s\'s to %3$s.', 'woocommerce-max-quantity' ),
$new_max,
$product->get_name(),
'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>'),
$new_max ),
'error' );
$passed = false;
}
if ( isset( $new_min) && ( $already_in_cart + $quantity ) < $new_min ) {
wc_add_notice( apply_filters( 'wc_qty_error_message', sprintf( __( 'You should have minimum of %1$s %2$s\'s to %3$s.', 'woocommerce-max-quantity' ),
$new_min,
$product->get_name(),
'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>'),
$new_min ),
'error' );
$passed = false;
}
return $passed;
}
add_filter( 'woocommerce_update_cart_validation', 'wc_qty_update_cart_validation', 1, 4 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment