Skip to content
Advertisement

Allow checkout only when a product of a mandatory category is in cart

I’d like to stop any customer advancing to the checkout if they do not have a particular product category in their basket. I would also like to tell them with an error message that they need to add a certain product. I’ve found some code but cannot it to work. I’ve added it as a code snippet into my WordPress install but alas it does not function and there are no error messages even though I have debugging switched on. Here is the code that I have found in Github that may need modification in order for this to work:

JavaScript

So I’m looking to stop checkout (with error message) if the ‘sibling’ category is the only item in the cart. I have a ‘standard’ category which must be in the basket before the customer makes it to the checkout. Hope this makes sense.

Advertisement

Answer

Here you have a solution that will make the trick. There is especially 2 main functions (the last ones):

  1. The first function (N°3) display your message on cart page, when there is something in cart but not the mandatory product category. Displays also the message on the mandatory product archive pages (useful when customer get redirected from checkout, see below).
  2. The second function (N°4) redirect customer to the product mandatory category archive pages when it tries to checkout and his cart has not that missing mandatory product category.

Define before your mandatory category slug in your_mandatory_category_slug() function.

This is the code:

JavaScript

This goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and fully functional.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement