Next we’ll need to be able to calculate the total of items in the matching category. Depending on how you are working with your fees and discounts, you may want to count the Items by Quantity or just count the amount of different items.
I’m using the Version where I just go with the number of different items but you do what suits your needs. You could combine these and make the quantity and item count a variable, but since I’m assuming most of you will need either one or the other, I suggest you just use one of them.
If we are working with percentage based Discounts that just apply to our matching items, we’ll need an additional function that calculates the total of all of our items.
The idea behind this function is, to create an array for every type of discount, where we would be able to enter Data and then iterate through all of those items and do the whole math and all.
Let’s have a bit of a closer look at the last part of that, the foreach loop. We have 3 conditions in our case which only need to be applied, if the item count of or the quantity count match a certain criteria, I decided to call this the apply count.
Then we have value based Fees and Discounts and Percentage based. If we want to use percentage, we need to get the total of the items and multiply it with our percentage to get the right fraction.
Since we do have Fees (adding value to the cart) and Discounts (removing value from the cart, thus creating a negative fee) we might have to multiply our entire charge with negative one to turn it into a discount. So for every Discount or Fee, we need to provided that information in an array.
Which brings me back to the Conditions and how we’d add them to make the function work.
if under 3 matching items are bought, apply a fee of $5
if 3 matching items are added, add a discount of 5%
if 4 or more matching items are added, add a discount of 10%
And then all that’s left is hook it into Woocommerce and we’re done.
And then you’ll be seeing your Discounts based on the Items in the Cart
I hope this was helpful and if you have any questions left, feel free to ask!