Repository › Forums › Support › WooCommerce Extended Coupon Features PRO › Buy 5 and get 2 (cheapest) for FREE › Reply To: Buy 5 and get 2 (cheapest) for FREE

#19346
Soft79
Keymaster

If you paste the following snippet to your child theme, you get an option ‘Limit discount to: Two cheapest of every n items’ that you can use.

1. Paste the snippet in your child theme’s functions.php
2. Create a new 100% discount coupon
3. On the ‘Usage restrictions’-tab set ‘Minimum quantity of matching products’ to: 7
4. On the ‘Usage limits’-tab set ‘Limit discount to’ to ‘Two cheapest of every n items’

That should do the trick!


add_filter( 'wjecf_get_limit_to_options',
    function ( $options ) {
        $options['two_cheapest_for_every_n_items'] = [
            'callback' => 'limit_to_two_cheapest_for_every_n_items',
            'title' => __( 'Two cheapest of every n items. n = min qty of matching products (or 2 if not supplied)', 'woocommerce-jos-autocoupon')
        ];
        return $options;
    }, 10, 1
);
function limit_to_two_cheapest_for_every_n_items( $coupon, $discountable_cart_items ) {
    //nth is the amount entered in 'minimum qty of matching products' or 2
    $nth = intval( WJECF_Wrap( $coupon )->get_meta( '_wjecf_min_matching_product_qty' ) );
    if ( empty( $nth ) ) {
        $nth = 2;
    }
    //Discountable items; cheap to expensive
    uasort(
        $discountable_cart_items,
        function ( $cart_item_a, $cart_item_b ) {
            $price_a = $cart_item_a['data']->get_price();
            $price_b = $cart_item_b['data']->get_price();
            return $price_a <=> $price_b;
        }
    );
    $limits = [];
    //First find the total number of items
    $total_items = 0;
    foreach( $discountable_cart_items as $cart_item_key => $cart_item ) {
        $total_items += $cart_item['quantity'];
    }
    //This amount of items should be discounted
    $discountable_items_left = 2 * floor( $total_items / $nth );
    foreach( $discountable_cart_items as $cart_item_key => $cart_item ) {
        $limits[$cart_item_key] = min( $discountable_items_left, $cart_item['quantity'] );
        $discountable_items_left -= $limits[$cart_item_key];
    }
    return $limits;
}