You can't avoid page reloading when using woocommerce_add_to_cart_validation
filter hook.
There is 2 cases when using woocommerce_add_to_cart_validation
filter hook:
1) Allow add to cart: You return the default filter hook argument (which is true
):
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 3 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity ) {
$a = 0; // <===
if( $a === 1 ){
$passed false; // Avoiding add to cart
// (Optional) Display a custom eror notice
wc_add_notice( __('Alert message: "add to cart avoided"', 'woocommerce' ), 'error' );
}
return $passed;
}
For ajax add to cart, the product will be added to cart (as by default) without reloading.
For normal add to cart, the product will be added to cart and the page will be reloaded as by default.
2) Avoid add to Cart: The condition in the IF
statement matches, the filter hook argument is set to false and returned (optionally you can display an error message):
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 3 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity) {
$a = 1;
// Any other value for $a than "1" will allow add to cart
if( $a === 1){
$passed false; // Avoid add to cart
// (Optional) Display a custom eror notice
wc_add_notice( __('Alert message: "add to cart avoided"', 'woocommerce' ), 'error' );
}
return $passed;
}
For ajax add to cart, customer will be redirected to the single product page (avoiding add to cart).
For normal add to cart, the page will be reloaded as by default (avoiding add to cart).
The only possible way to avoid page reloading should be to use a custom (Ajax) jQuery script, meaning that you should build your own validation functionality.