Скидка для определенной категории на основе общего количества товаров

В WooCommerce у меня есть категория продуктов под названием "Образцы", каждый образец стоит $2,99. Но я бы хотел, чтобы способ автоматически изменить стоимость образцов с 2,99 до 1 доллара при добавлении 5 образцов в корзину.

Таким образом, если в корзину будет добавлено 4 образца, общая сумма составит $ 11,96… но если добавить 5, общая сумма составит $ 5.

Таким образом, для каждых 5 продуктов цена продукта изменится с 2,99 долл. До 1 долл., Но если в корзину будет добавлено 6 образцов, общая сумма составит 7,99 долл., А при добавлении 10 - 10 долл. И т. Д.

Как я мог этого добиться?

Благодарю.

1 ответ

Решение

Обновление - добавлена ​​совместимость с Woocommerce 3.

Вот то, что должно быть удобно для ваших требований.
Эта функция добавит скидку в корзину:

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 вашей активной дочерней темы (или активной темы). Проверено и работает.

Другие вопросы по тегам