Search code examples
phpwordpresswoocommercecartdiscount

Discounting the cheapest item for a specific category in WooCommerce


I wound like to discount the cheapest cart item in Woocommerce, based on a product category. Based on "Cart discount for product that cost less in Woocommerce" answer code that works perfectly.

But how to make it work for a specific product category only.

The idea is to have 2 products in the shopping cart and have a discount on the cheapest item for a specific product category.


Solution

  • Updated - Limiting to 2 items from the defined product category.

    The following will do the same for a specific product category (to be defined in the code):

    add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
    function discount_on_cheapest_cart_item( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Settings
        $categories = ['tshirts']; // Your product categories (coma separated)
        $percentage = 10; // 10 % discount
    
        // Only for 2 items or more
        if ( $cart->get_cart_contents_count() < 2 ) return;
    
        // Initialising
        $discount = 0;
        $item_prices = array();
    
        // Loop though each cart items and set prices in an array
        foreach ( $cart->get_cart() as $cart_item ) {
            if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
                $product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
            }
        }
    
        // We set the fee for 2 items of the defined product category
        if( count($product_prices_excl_tax) == 2 ) {
    
            sort($product_prices_excl_tax);
    
            $discount = reset($product_prices_excl_tax) * $percentage / 100;
    
            $cart->add_fee( sprintf( __("Discount on cheapest %s"), '('.$percentage.'%)' ), -$discount );
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should works.