Skip to content

Instantly share code, notes, and snippets.

@claudiosanches
Last active June 22, 2018 16:57
Show Gist options
  • Save claudiosanches/4527041 to your computer and use it in GitHub Desktop.
Save claudiosanches/4527041 to your computer and use it in GitHub Desktop.
WooCommerce: Validate cart quantity.
<?php
/**
* Validate product quantity when added to cart.
*/
function cs_add_to_cart_validate_quantity( $valid, $product_id, $quantity ) {
global $woocommerce;
$valid = true;
// Test quantity.
if ( 50 > $quantity ) {
// Sets error message.
$woocommerce->add_error( __( 'A quantidade m&iacute;nima &eacute; de 50!' ) );
$woocommerce->set_messages();
$valid = false;
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'cs_add_to_cart_validate_quantity', 10, 3 );
/**
* Validate product quantity on cart update.
*/
function cs_update_validate_quantity( $valid, $cart_item_key, $values, $quantity ) {
global $woocommerce;
$min_quantity = 50;
$valid = true;
// Test quantity.
if ( $min_quantity > $quantity ) {
// Sets error message.
$woocommerce->add_error( sprintf( __( 'A quantidade m&iacute;nima &eacute; de %s!' ), $min_quantity ) );
$woocommerce->set_messages();
$woocommerce->cart->set_quantity( $cart_item_key, $min_quantity );
$valid = false;
}
return $valid;
}
add_filter( 'woocommerce_update_cart_validation', 'cs_update_validate_quantity', 1, 4 );
@AdsonCicilioti
Copy link

Opa! Muito bom estava mesmo atrás desta validação. Valew Cláudio!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment