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!
$redirect
try to addglobal $woocommerce;
– Firefog