在WooCommerce中,我有一類稱爲樣品的產品,每個樣品的成本爲2.99美元。 但是,我想要一種方法,當5個樣品添加到購物車時,將樣品的成本自動從$ 2.99更改爲$ 1。基於產品總數的某種類別的折扣
因此,如果將4個樣品添加到購物車,總數將是11.96美元......但如果添加5個,總數將是5美元。
因此,對於每5種產品,產品價格將改變從$ 2.99 $ 1,但如果6個樣品添加到購物車總數爲$ 7.98和是否添加10的總數是10等$ ...
我怎麼能做到這一點?
謝謝。
在WooCommerce中,我有一類稱爲樣品的產品,每個樣品的成本爲2.99美元。 但是,我想要一種方法,當5個樣品添加到購物車時,將樣品的成本自動從$ 2.99更改爲$ 1。基於產品總數的某種類別的折扣
因此,如果將4個樣品添加到購物車,總數將是11.96美元......但如果添加5個,總數將是5美元。
因此,對於每5種產品,產品價格將改變從$ 2.99 $ 1,但如果6個樣品添加到購物車總數爲$ 7.98和是否添加10的總數是10等$ ...
我怎麼能做到這一點?
謝謝。
- 更新 -
這裏是什麼,應該是方便您的要求。
此功能將增加折扣購物車:
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)
}
當我使用上面的代碼時,我在購物車中有5個樣品,每個產品的總價格爲2.99美元,總計爲14.95美元,它適用於總計爲10美元的「4.95美元」的「數量折扣」。最終的總數將是5美元而不是10美元。 –
完美謝謝! –
你告訴我們你需要什麼,但是你還沒有告訴我們你已經嘗試過什麼,什麼是行不通的。我們該怎樣幫助你? – byxor