Discount for a certain category based on the total number of products

In WooCommerce, I have a product category called Samples, each sample costs $ 2.99. But I would like to automatically change the cost of samples from 2.99 to 1 US dollar when 5 samples are added to the basket.

So, if 4 samples were added to the basket, the total would be $ 11.96 ... but if 5 were added, the total would be $ 5.

So, for every 5 products, the price of the product will change from $ 2.99 to $ 1, but if 6 samples were added to the basket, the total would be $ 7.99, and if 10 were added, the total would be $ 10 ...

How could I achieve this?

Thank.

+1
source share
1 answer

- Updated -

Here's what should be convenient for your requirements.
This feature will add a discount to the cart:

add_action( 'woocommerce_cart_calculate_fees','custom_cart_discount', 10, 1 );
function custom_cart_discount( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Define HERE your targeted product category (id, slug or name are accepted)
    $category = 'posters';
    // Set the price for Five HERE
    $price_x5 = 5;

    // initializing variables
    $calculated_qty = 0;
    $calculated_total = 0;
    $discount = 0;

    // Iterating through each cart item
    foreach($cart_object->get_cart() as $item_key => $item):

        // Make this discount calculations only for products of your targeted category
        if(has_term($category, 'product_cat', $item['product_id'])):

            $item_price = $item["data"]->price; // The price for one (assuming that there is always 2.99)
            $item_qty = $item["quantity"];// Quantity
            $item_line_total = $item["line_total"]; // Item total price (price x quantity)
            $calculated_qty += $item_qty; // ctotal number of items in cart
            $calculated_total += $item_line_total; // calculated total items amount
        endif;
    endforeach;

    // ## CALCULATIONS (updated) ##
    if($calculated_qty >= 5):      
        for($j = 5, $k=0; $j <= $calculated_qty; $j+=5,$k++); // Update $k=0 (instead of $k=1)
        $qty_modulo = $calculated_qty % 5;
        $calculation = ( $k * $price_x5 ) + ($qty_modulo * $item_price);
        $discount -= $calculated_total - $calculation;
    endif;

    // Adding the discount 
    if ($discount != 0)
        $cart_object->add_fee( __( 'Quantity discount', 'woocommerce' ), $discount, false );
        // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
}
+3
source

Source: https://habr.com/ru/post/1662979/


All Articles