基于产品总数的特定类别折扣

Discount for Certain Category Based on Total Number of Products

在 WooCommerce 中,我有一类产品称为样品,每个样品售价 2.99 美元。 但我想要一种方法,可以在将 5 个样品添加到购物车时自动将样品成本从 2.99 美元更改为 1 美元。

因此,如果将 4 个样品添加到购物车,则总计为 11.96 美元……但如果添加 5 个,则总计为 5 美元。

因此,对于每 5 件产品,产品价格将从 2.99 美元变为 1 美元,但如果将 6 件样品添加到购物车,则总价为 7.99 美元,如果添加 10 件,则总价为 10 美元,依此类推...

我怎样才能做到这一点?

谢谢。

UpdateAdded Woocommerce 3 compatibility.

这里有一些应该方便您的要求。
此功能将为购物车添加折扣:

add_action( 'woocommerce_cart_calculate_fees','custom_cart_discount', 20, 1 );
function custom_cart_discount( $cart ) {

    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->get_cart() as $cart_item):

        // Make this discount calculations only for products of your targeted category
        if(has_term($category, 'product_cat', $cart_item['product_id'])):
            $item_price = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->price : $cart_item['data']->get_price(); // The price for one (assuming that there is always 2.99)
            $item_qty = $cart_item["quantity"];// Quantity
            $item_line_total = $cart_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->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)
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。