Don’t redirect to WooCommerce product single page after “add-to-cart” error

When you face an error during adding a product to cart on WooCommerce shop or any other archive page, it redirects you to the product single page with an error message. Today our goal is to stop that redirect and stay on the shop or the archive page – wherever we were.

This is very simple, thanks to woocommerce_cart_redirect_after_error filter. We just need to pass false to stop the redirection during an error.

function careless_custom_add_to_cart_redirect_after_error( $url ) {
    return false;
}
add_filter( 'woocommerce_cart_redirect_after_error', 'careless_custom_add_to_cart_redirect_after_error' );

Alternatively we can simply use the __return_false function like below:

add_filter( 'woocommerce_cart_redirect_after_error', '__return_false' ); 

Code goes in the functions.php file of your active theme.