[英]Bulk Discount for specific product ID in WooCommerce
I want to discount a specific product during checkout based on quantity thresholds:我想在结账时根据数量阈值打折特定产品:
Sample Desired Output example:示例所需输出示例:
so far I have this, but when I add 10 units of the product to cart I get a critical error.到目前为止,我有这个,但是当我将 10 个单位的产品添加到购物车时,出现严重错误。
My code:我的代码:
add_action( 'woocommerce_before_calculate_totals', 'quantity_based_pricing', 9999 );
function quantity_based_pricing( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Define discount rules and thresholds
$threshold1 = 10; // Change price if items > 10
$discount1 = 0.02739726027; // Reduce 73 dollar unit price by 2 dollars
$threshold2 = 20; // Change price if items > 20
$discount2 = 0.04109589041; // Reduce 73 dollar unit price by 3 dollars
//compare
foreach ( $cart->get_cart() as $cart_item_key => $cart_item )
// Get product id
$product_id = $cart_item['product_id'];
if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 && $cart_item = '283' ) {
$price = round( $cart_item['data']->get_price() * ( 1 - $discount1 ), 2 );
$cart_item['data']->set_price( $price );
} elseif ( $cart_item['quantity'] >= $threshold2 && in_array( $product_id, $specific_product_ids ) ) {
$price = round( $cart_item['data']->get_price() * ( 1 - $discount2 ), 2 );
$cart_item['data']->set_price( $price );
}
}
What am I doing wrong?我究竟做错了什么? How to make that work without errors?
如何使这项工作没有错误?
There are some mistakes in your code.您的代码中有一些错误。 Try the following instead:
请尝试以下操作:
function quantity_based_pricing_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Define discount rules and thresholds
$threshold1 = 10; // Change price if items > 10
$threshold2 = 20; // Change price if items > 20
$discount_1 = 2; // Reduce unit price by 2 dollars
$discount_2 = 3; // Reduce unit price by 3 dollars
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Targeting specific product id
if( $cart_item['product_id'] == '283' ) {
$price = $cart_item['data']->get_price();
$qty = $cart_item['quantity'];
if ( $qty >= $threshold1 && $qty < $threshold2 ) {
$discount = $discount_1;
} elseif ( $qty >= $threshold2 ) {
$discount = $discount_2;
}
if ( isset($discount) ) {
$cart_item['data']->set_price( round( $price - $discount, 2 ) );
}
}
}
}
Code goes in functions.php file of the active child theme (or active theme).代码位于活动子主题(或活动主题)的 functions.php 文件中。 Tested and works.
测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.