Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce redirect after add-to-cart error

I have being doing research for a few days but still cannot find an answer.

I am using Woocommerce without the Single Product page. So I am using urls like http://domain.com/?add-to-cart=ID to add products to cart.

My products are sold individually which means that I can only add the product to cart once. Now when I add a product for the first time, I am redirected to the cart page which is what I wanted. However, when I add the product the second time, it is refreshing the page I am on. But I want to be redirected to the cart page and shown the error message like 'You cannot add the product twice' on the cart page.

When I was reading the Woocommerce core source code, I found the code below in the add-to-cart() function in file class-wc-ajax.php.

// If there was an error adding to the cart, redirect to the product page to show any errors
        $data = array(
            'error'       => true,
            'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id )
        );

        wp_send_json( $data );

So I tried to add a filter by adding the code below in my theme functions.php file.

function filter_woocommerce_cart_redirect_after_error($redirect, $product_id) {
  $redirect = esc_url( WC()->cart->get_cart_url() );
  return $redirect;
}

add_filter( 'woocommerce_cart_redirect_after_error', 'filter_woocommerce_cart_redirect_after_error', 10, 2 );

But nothing was changed.

Can anyone help? Thanks!

like image 831
C.Yu Avatar asked Sep 04 '25 01:09

C.Yu


1 Answers

This is the default option that is build into WooCommerce. You can find the option in the WooCommerce -> Settings -> Products -> Display area. When the option “Redirect to the cart page after successful addition” is checked it will redirect all users to the cart after adding a product to the cart. Follow this

enter image description here

You can redirect to cart page when you get error

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

You can also use to redirect to checkout page

function firefog_custom_add_to_cart_redirect( $url ) {
    $url = WC()->cart->get_checkout_url();
    return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'firefog_custom_add_to_cart_redirect' );
like image 167
Firefog Avatar answered Sep 07 '25 09:09

Firefog