Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Validation on Add To Cart button click action
<?php
/*
* Validating the quantity on add to cart action with the quantity of the same product available in the cart.
*/
function wc_qty_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {
$product_min = wc_get_product_min_limit( $product_id );
$product_max = wc_get_product_max_limit( $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;
}
}
$already_in_cart = wc_qty_get_cart_qty( $product_id );
$product = wc_get_product( $product_id );
$product_title = $product->get_title();
if ( !is_null( $new_max ) && !empty( $already_in_cart ) ) {
if ( ( $already_in_cart + $quantity ) > $new_max ) {
// oops. too much.
$passed = false;
wc_add_notice( apply_filters( 'isa_wc_max_qty_error_message_already_had', sprintf( __( 'You can add a maximum of %1$s %2$s\'s to %3$s. You already have %4$s.', 'woocommerce-max-quantity' ),
$new_max,
$product_title,
'<a href="' . esc_url( wc_get_cart_url() ) . '">' . __( 'your cart', 'woocommerce-max-quantity' ) . '</a>',
$already_in_cart ),
$new_max,
$already_in_cart ),
'error' );
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'wc_qty_add_to_cart_validation', 1, 5 );
/*
* Get the total quantity of the product available in the cart.
*/
function wc_qty_get_cart_qty( $product_id ) {
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'] ) {
$running_qty += (int) $values['quantity'];
}
}
return $running_qty;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment