How to clear cart before adding a new subscription product?

I am in need of a way to clear the cart and add a new product when a customer adds a subscription product to the cart. We often have customers accidentally purchase multiple subscription products which we need to refund.

  1. Customer visits one of our subscription product pages

  2. Completes dropdown selections and adds to cart → check if cart is empty and if not, clear cart and add new subscription product

  3. Ideally, we would like to clear the cart, add the items, then go directly to ReCharge checkout without the user ever having to land on the cart

Any assistance would be greatly appreciated.

What if they have other items in the cart that arent associated with whatever subscription they’re adding? Do you always want to clear the cart?

Hi @Ninthony , we can always clear the cart.

If that’s the case there’s a couple of things you have to do. You have to locate your add to cart button in your product template and give it a special class if it’s a subscription item. So let’s just for the sake of argument say that if your product is a subscription item, you tag it with “subscription-item”. When you find your add to cart button, you’re going to want to make a condition in the class attribute to add a class if it’s tagged with “subscription-item”. The class I’m going to add will also be called “subscription-item” just for simplicity, you can name the class whatever you’d like, but you’ll need to be sure to change it in the querySelector in the javascript later. Also, you’re going to want to add the subscription item’s variant id in a data attribute on the button. So all of that might look something like this:


Then you'll want to go into theme.liquid and add this right before the closing body tag, which looks like this </body> :

```javascript

I commented it out so you may be able to understand it a bit better, and I also did it all in vanilla JS in case you don’t have jQuery on your theme. Ideally this would use fetch but it’s not supported in IE so I used XMLHttpRequest just in case that’s necessary. Let me know if you need help.

I will follow up via private message. I have implemented the solution but unfortunately there are several variables that are complicating the result.

As an update, @Ninthony was able to provide a working solution. I highly recommend them if you have some more custom needs on your store.