Banner

3×2 Offer Product Discount

Automatic 3x2 offer system that applies "Buy 2, Get 1 Free" discount.

Display estimated delivery date
PHP
/**
 * Snippet Name:     WooCommerce Offer Product Discount
 * Snippet Author:   coding-bunny.com
 * Description:      Automatic 3x2 offer system that applies "Buy 2, Get 1 Free" discount.
 * Version:          1.0.0
 */

class CBOPD_WC_Offer_Product_Discount {
    
    public function __construct() {
        add_action('woocommerce_cart_calculate_fees', array($this, 'cbopd_apply_3x2_discount'));
    }
    
    public function cbopd_apply_3x2_discount() {
        if (is_admin() && !defined('DOING_AJAX') || !WC()->cart->get_cart_contents_count()) {
            return;
        }
        
        $cart_items = WC()->cart->get_cart();
        $product_prices = array();
        
        foreach ($cart_items as $cart_item_key => $cart_item) {
            $product_price = $cart_item['data']->get_price();
            $quantity = $cart_item['quantity'];
            
            for ($i = 0; $i < $quantity; $i++) {
                $product_prices[] = floatval($product_price);
            }
        }
        
        if (count($product_prices) < 3) {
            return;
        }
        
        rsort($product_prices);
        
        $free_items = floor(count($product_prices) / 3);
        $total_discount = 0;
        
        for ($i = 0; $i < $free_items; $i++) {
            $index = ($i * 3) + 2;
            if (isset($product_prices[$index])) {
                $total_discount += $product_prices[$index];
            }
        }
        
        if ($total_discount > 0) {
            WC()->cart->add_fee(__('3x2 Offer Discount', 'woocommerce'), -$total_discount);
        }
    }
}

if (class_exists('WooCommerce')) {
    new CBOPD_WC_Offer_Product_Discount();
}
?>

How To Implement This Solution?

Leave a Reply

My Agile Privacy
This site uses technical and profiling cookies. You can accept, decline or customize cookies by pressing the desired buttons. By closing this policy you will continue without accepting.

Need help?

Choose one of the following options:

Powered by CodingBunny