How to add validation on add to cart button?

In this tutorial we’ll learn how to add validation to add to cart button. There come some requirements where we have to apply this.

Let’s have an example for this kind of scenario: Let’s say we have a product named “Both shoes”, and a product “left shoe”. A user adds “left shoe” to the cart. Then he adds “both shoes”. In this casewe may want to print an error instead of adding the “both shoes”: Sorry, but you can’t add both shoes if you’ve added left shoe to the cart. If you want to buy “both shoes”, please first remove “left shoe”.

So, to this add the following lines of code at the end of your theme’s functions.php file:

function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {

 

// do your validation, if not met switch $passed to false

if ( 1 != 2 ){

$passed = false;

wc_add_notice( __( 'You can not do that', 'textdomain' ), 'error' );

}

return $passed;

 

}

add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );

You can access functions.php file here:

woocommerceHere in the ‘if’ statement you can apply the condition/validation you want to apply before adding a product to cart. Here you can also set the validation but replacing the text on line 6.

I’ve applied a condition which is meant to be true just for the example purpose i.e. 1 != 2.

Now after placing this code when we’ll try to add product to cart we’ll receive error:

woocommerceIn this way you can set any validation rule and message before adding a product to cart.

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

Leave a Comment

Your email address will not be published. Required fields are marked *