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!
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 businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 8
* @community https://businessbloomer.com/club/
*/
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 );
}
}
}
Advanced Plugin: WooCommerce Discount Manager
For a no-code alternative, you can also create deals on the cheapest item using the WooCommerce Discount Manager plugin by Barn2. This flexible plugin lets you create a wide range of discounts and deals, such as BOGO offers and buy-one-get-one-half-price. It always applies the deal to the cheapest item.
https://barn2.com/wp-content/uploads/2024/01/WooCommerce-discount-plugin-Add-New-discount-popup.png