How do I redirect to the cart page if I click on the 'Add to cart' button for a product that's already in cart?
Woocommerce/wordpress:
This is my code currently. At the moment it is not redirecting to the cart page.
add_filter( 'woocommerce_add_to_cart_redirect', 'woo_in_cart' );
function woo_in_cart($product_id) {
global $woocommerce;
$url = WC()->cart->get_cart_url();
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val['data'];
if($product_id == $_product->id ) {
wp_redirect($url);
}
}
}
this snippet does what you asked for, and it supports ajax calls. some points about with your code:
1- 'woocommerce_add_to_cart_redirect' fires when product is already added to cart.
2- WC()->cart->get_cart_url() is deprecated
3- will not redirect if ajax add to cart is enabled
add_filter('woocommerce_add_to_cart_validation' , 'shalior_flag_already_added_products_as_invalid' , 10 , 2);
function shalior_flag_already_added_products_as_invalid ($result , $product_id){
if (false === $result){
return $result;
}
$url = wc_get_cart_url();
foreach ( WC()->cart->get_cart() as $cart_item ) {
$cart_item_product_id = $cart_item['product_id'];
if($product_id === $cart_item['product_id'] ) {
$result = false;
}
}
if (false === $result){
add_filter('woocommerce_cart_redirect_after_error' , function (){
return wc_get_cart_url();
} , 999 );
}
return $result;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.