I have a wordpress shop, where I sell digital products.
What the function should do:
- User clicks add to cart button.
- Function checks if the item is already in the cart.
- If yes: Redirect user to checkout page without adding the product to cart (so the quantity doesn't change, it stays at 1).
- If no: Redirect to checkout and add product to cart (quantity goes from 0 to 1).
What the function looks like:
add_filter('woocommerce_add_to_cart_validation', 'my_validation_handler', 10, 2);
function my_validation_handler($is_valid, $product_id) {
$url = WC()->cart->get_checkout_url();
foreach(WC()->cart->get_cart() as $cart_item_key => $values) {
if ($values['data']->id == $product_id) {
$url = WC()->cart->get_checkout_url();
wp_redirect($url);
exit();
}
else {
return $is_valid;
}
}
}
What happens:
When I implement the code in the functions.php of my child theme: (I already have the product in the cart) I click on the add to cart button again, but nothing happens.
If the cart is empty same thing, nothing happens, no reload nothing, I'm still on the products page.
Important detail:
I know there is a native WooCommerce function (sold seperately). But I have a custom products page and I don't want a message to appear that says "you already added that to cart".
Since I'm retargeting website visitors, the item is still in there sometimes from their last visit. And a expire session solution also not really what I'm looking for.