I'm trying to add a gift product to a shopping cart based upon the total cost spent by a customer. It's for a restaurant that sells gift vouchers. The scheme runs as follows: for every £50 that a customer spends in a single transaction, they automatically receive a £10 gift voucher for free. So, if they spend £100 on gift vouchers, they receive 2x £10 gift vouchers for free (and so on). To keep things as simple as possible, we're limiting denominations of gift vouchers (£25 - £250 increasing in £25 denominations). I don't particularly want to pay for/install another plugin that will need to be updated/managed, etc. If I'm honest, it's only for the Christmas period so a snippet of code to do this would be far better. The way I see it working is that a customer adds the vouchers to the cart and when they go to the cart it shows they've also got the additional 'free' vouchers in there too.
I've found some code online and made some changes to it. The code is as follows:
function auto_add_specific_product_to_cart() {
// select product ID
$product_id = 1428;
// if cart empty, add it to cart
if ( WC()->cart->get_cart_total() <= 99 ) {
WC()->cart->add_to_cart( $product_id, 1 ); }
else if ( WC()->cart->get_cart_total() <= 149 ) {
WC()->cart->add_to_cart( $product_id, 2 ); }
else if ( WC()->cart->get_cart_total() <= 199 ) {
WC()->cart->add_to_cart( $product_id, 3 ); }
else if ( WC()->cart->get_cart_total() <= 249 ) {
WC()->cart->add_to_cart( $product_id, 4 ); }
}
I'm having problems with it right, left and centre. It keeps adding the free vouchers to the shopping cart so eventually customers end up with 20 or 30 vouchers there; the PHP for recognising the different thresholds (50 to 99, 100 to 149, etc) aren't working properly. I'm probably making this far too complicated and not thinking it through but a bit of help would be great. I've found plenty of code online for discounting products but nothing that gives something away for free.