skip to Main Content

I’m adding to the WooCommerce cart via redirecting to an add-to-cart url. For example, my code generates this URL and redirects to it:

/?add-to-cart=2316723&variation_id=2316727&attribute_program=General&nyp=10

I have to add to cart this way since I’m using the Name Your Price add-on, and so I can’t add to cart via WC()->cart->add_to_cart()

Unfortunately, when there is an error in adding to cart, WooCommerce redirects to my home page, instead of staying on the cart so that the user can see the error.

This does not happen when there’s a cart error after a customer clicks a product button to add to cart, but only when there’s a cart error after my code redirects to the add-to-cart url.

I have tried this filter:

    add_filter( 'woocommerce_cart_redirect_after_error', 'stop_woo_cart_redirect');
function stop_woo_cart_redirect( $url ) {
        $url = WC()->cart->get_cart_url();
        return $url;
}

and it doesn’t make a difference.

The cart error is usually from some of my other, using woocommerce_add_to_cart_validation filter.

So, in other words, my code generates an add-to-cart URL and redirects to it, my other code determines that specific product mix is invalid and generates a cart error, but WooCommerce does not stay on the cart, but redirects away from it.

Is there any way I can fix this?

2

Answers


  1. As you can’t use WC()->cart->add_to_cart() I doubt WC()->cart->get_cart_url(); will work. You will need to hook into using your custom code.

    Try this. I have no idea if it will work but worth a shot.

    add_filter( ‘woocommerce_cart_redirect_after_error’, ‘__return_false’ );

    Login or Signup to reply.
  2. For someone still having this issue I managed to redirect to the cart page using the template redirect hook like so:

    add_action('template_redirect', function () {
        $addToCartQuery = intval($_GET['add-to-cart']);
        if (is_front_page() && !empty($addToCartQuery)) {
            wp_safe_redirect(WC()->cart->get_cart_url());
            exit();
        }
    });
    

    This code checks, if the user is currently on the landing page and the add-to-cart parameter is present.
    For security, I am using intval to sanitize the raw get parameter since it’s not available via get_query_var() function.

    If you want to receive the query var using this safe wordpress function, you may as well add it using the following filter:

    add_filter('query_vars', function ($vars) {
        $vars[] = 'add-to-cart';
        return $vars;
    }, 10, 1);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search