Menu Close

WooCommerce: Apply Discount to Cheapest Cart Item

default

If you run WooCommerce store promotions, this little snippet will help you with that. For example, how to run a “Buy 2 products, get one half off” or a “Buy 3 products, get the cheapest one for free” campaign?

The trick behind this workaround is to find the cheapest item by looping through the cart, and then to set its price so that it’s lower than the regular price. Enjoy!

With the help of the snippet below, I was able to discount the cheapest item in the cart by 50%!

PHP Snippet: Set The Cheapest Product Sale Price @ WooCommerce Cart

The snippet below applies a 50% discount to the cheapest item in the cart (also called BOGO 50 = Buy One Get One 50% Off).

If you wish to see the “slashed price” in the cart as per the screenshot above, you can use my WooCommerce: Display Regular & Sale Price @ Cart Table snippet.

/**
 * @snippet       Discount Cheapest Cart Item
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 8
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

add_action( 'woocommerce_before_calculate_totals', 'bbloomer_cheapest_cart_item_half_off', 9999 );
 
function bbloomer_cheapest_cart_item_half_off( $cart ) {
 
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
 
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
 
    if ( count( $cart->get_cart() ) < 2 ) return; // AT LEAST 2 PRODUCTS IN THE CART

    $min = PHP_FLOAT_MAX;
 
    // LOOP THROUGH CART TO FIND CHEAPEST ITEM
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
      if ( $cart_item['data']->get_price() <= $min ) {
         $min = $cart_item['data']->get_price();
         $cheapest = $cart_item_key;
      }
    }

    // LOOP THROUGH CART TO REDUCE CHEAPEST ITEM PRICE BY 50%
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
      if ( $cheapest == $cart_item_key ) {
         $price = $cart_item['data']->get_price() / 2;
         $cart_item['data']->set_price( $price );
		   $cart_item['data']->set_sale_price( $price );
      }
    }
    
 }
View Source
Posted in WooCommerce Tips