简体   繁体   中英

Auto add a variable quantity of specific product based on WooCommerce cart subtotal

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.

Here a variable quantity of a "specific product voucher" will be auto added to cart based on cart subtotal.

The code below is based on Add free gifted product for a minimal cart amount in WooCommerce answer code. The code automate the generation of cart subtotal thresholds (min and max amounts) and the related quantity of the voucher product to be added to cart.

The number set in $max_quantity variable, determines the number of iterations on the FOR loop (so the number of different generated thresholds and the max quantity of voucher product that can be added to cart) .

// Auto add a quantity of voucher product based on cart subtotal
add_action( 'woocommerce_before_calculate_totals', 'auto_add_voucher_product_based_on_subtotal' );
function auto_add_voucher_product_based_on_subtotal( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Settings
    $voucher_product_id = 37; // Voucher product Id
    $max_quantity       = 20; // Here set the max item quantity (for voucher product)
    $min_subtotal       = 50;  // Starting threshold min amount
    $cart_subtotal      = 0;  // Initializing

    // Loop through cart items (first loop)
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // When voucher product is is cart
        if ( $voucher_product_id == $cart_item['product_id'] ) {
            $voucher_key = $cart_item_key;
            $voucher_qty = $cart_item['quantity'];
            // $cart_item['data']->set_price(0); // (optional) set the price to zero
        } else {
            $cart_subtotal += $cart_item['line_total'] + $cart_item['line_tax']; // Get subtotal
        }
    }

    // If voucher product is not already in cart, add it
    if ( ! isset($voucher_key) && $cart_subtotal >= $min_subtotal ) {
        $cart->add_to_cart( $voucher_product_id );
    }
    // Check vouvher product quantity and adjust it depending on the subtotal amount.
    else {
        // Loop dynamically through subtotal threshold min and max amounts setting the right quantity
        // $i is the min amount, $j the max amount and $q the related quantity to check
        for ( $i = $min_subtotal, $j = 100, $q = 1; $q < $max_quantity; $i += 50, $j += 50, $q++ ) {
            if ( $cart_subtotal >= $i && $cart_subtotal < $j && $voucher_qty != $q ) {
                $cart->set_quantity( $voucher_key, $q );
            }
        }
        if ( $cart_subtotal >= $i && $voucher_qty != $q ) {
            $cart->set_quantity( $voucher_key, $q );
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM