• Resolved sonichka93

    (@sonichka93)


    I still have the possibility to add a code to Woocommerce so that when user applying a certain coupon, the 2nd product is a 50% discount.

    I find this code. It is working, but it’s just not aimed to the cheapest product. Where is an error ? Thank you very much

    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;
        } }
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘WooCommerce aimed the cheapest item on the cart – error in the code’ is closed to new replies.