0

I want to give users Buy one get another for 50% off, my concept is there is a coupon and :

condition 1) If user adds two item to the cart, the lowest priced item gets 50% discount. (I have achieved this, code is below)

condition 2) If user adds three items to the cart, the lowest priced item gets 50% discount. (same rule as number 1, I have achieved this.)

condition 3) If user adds four items to the cart, the lowest priced item + the second priced item gets 50% discount each. (help please)

Condition 4) If user adds six items to the cart, the lowest three items gets 50% off. (need help)

CODE :

add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_wc_coupon_get_discount_amount', 10, 5 );
function filter_wc_coupon_get_discount_amount( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) { 
    //Already created coupon code for which this code is to be executed.
    $coupon_code = 'test50';

    // Only when $coupon_code is used
    if( strtolower( $coupon_code ) !== $coupon->get_code() ) 
        return $discount_amount;

    $items_prices = [];
    $items_count  = 0;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $key => $item ){
        // Get the cart item price (the product price)
        if ( wc_prices_include_tax() ) {
            $price = wc_get_price_including_tax( $item['data'] );
        } else {
            $price = wc_get_price_excluding_tax( $item['data'] );
        }

        if ( $price > 0 ){
            $items_prices[$key] = $price;
            $items_count       += $item['quantity'];
        }
    }

    // Only when there is more than one item in cart
    if ( $items_count > 1 ) {
        asort($items_prices);  // Sorting prices from lowest to highest

        $item_keys = array_keys($items_prices);
        $item_key  = reset($item_keys); // Get current cart item key

        // Targeting only the current cart item that has the lowest price
        if ( $cart_item['key'] == $item_key ) {
            return ((($price)/100)*50); // return the lowest item price as a discount
        }
    } else {
        return 0;
    }
}

Above code credit : Apply a 100% coupon discount on the cheapest cart item in WooCommerce

  • Is it the intention that a coupon is required for this or do you always want to apply these discounts (even without a coupon) if the conditions are met? – 7uc1f3r Dec 06 '20 at 06:18
  • hi, thanks for your response. It is with a coupon. Already the first two conditions are met for the 3rd and 4th condition to meet, I tried to edit the code but could not succeed so I posted it here. – Sworup Timalsina Dec 06 '20 at 06:21

0 Answers0