More validation using WPC & WooCommerce
If you want to do more validation before adding a product to the cart (For example if you want to check "height + width" is less than a predetermined value), then this article is for you.
Using WooPrice Calculator you can set a minimum and maximum values for each field but you cannot validate more complex rules.
With Wordpress, WooPrice Calculator and WooCommerce this is really simple by using filters. You can use the filter "woocommerce_add_to_cart_validation" to do that.
How to make the validation?
For example, if you want check "height + width" must be less then 2000, you can append this new PHP function to your "functions.php" file, located in "/wp-content/themes/YOUR_THEME/": path.
function filter_custom_wpc_add_to_cart_validation($bool, $product_id, $quantity){ if($product_id == 40){ $width = $_REQUEST['aws_price_calc_1']; $height = $_REQUEST['aws_price_calc_2']; if(($width+$height) >= 2000){ wc_add_notice("Width and Height are greater then 2000 mm", "error"); return false; } } return true; } add_filter('woocommerce_add_to_cart_validation', 'filter_custom_wpc_add_to_cart_validation', 20, 3);
Where in this case:
- 40: this is the Product ID you want to check. You would like to change it for your products.
- aws_price_calc_N: These are the fields you want to check. You can get the fields ID from your calculator which you want to validate.
- ($width+$height) >= 2000: This is the condition you want to validate.
- wc_add_notice: The error message you want to show.
If validation fails, your customers will not be able to add the product to the cart and an error message will be shown like below: