0

I have this code

/*
*   Redirect to checkout after adding to cart
*/
function themeprefix_add_to_cart_redirect() {
  global $woocommerce;
  $checkout_url = $woocommerce->cart->get_checkout_url();
  return $checkout_url;
}
add_filter('add_to_cart_redirect', 'themeprefix_add_to_cart_redirect');

The problem is clicking on a link like www.example.com/?add-to-cart=1234 will not trigger the add_to_cart_redirect hook if there is something already in the cart. It thinks that there is something already in the cart and there is nothing else to add. Only one of my products can be purchased at a time.

Where can I hook in to redirect at an earlier stage in the cart validation process?

or

Is there a way to empty the cart before adding the product 1234?

Thanks!

1

Q: Is there a way to empty the cart before adding the product 1234?

A: Before adding a product to the cart, it is possible to empty the cart so that the add_to_cart_redirect hook will always be called. Use the woocommerce_add_to_cart_validation hook to alter the cart before adding a new item.

/**
 * First clear the cart of all products
 */
function clear_cart_before_adding( $cart_item_data ) {
  global $woocommerce;
  $woocommerce->cart->empty_cart();

  return true;
}
add_filter( 'woocommerce_add_to_cart_validation', 'clear_cart_before_adding' );

/**
*   Redirect to checkout after adding to cart
*/
function themeprefix_add_to_cart_redirect() {
  global $woocommerce;
  $checkout_url = $woocommerce->cart->get_checkout_url();
  return $checkout_url;
}
add_filter('add_to_cart_redirect', 'themeprefix_add_to_cart_redirect');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.