[英]WooCommerce progressive quantity discount for specific product categories
如果您的購物車中有超過 1 個產品,我正在研究一種提供累進折扣的方法。 我找到了這個線程並實際使用了這段代碼:
//Discount by Qty Product
add_action( 'woocommerce_before_calculate_totals', 'quantity_based_pricing', 9999 );
function quantity_based_pricing( $cart ) {
global $product;
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;
// Define discount rules and thresholds and product ID
$threshold1 = 2; // Change price if items > 1
$discount1 = 10; // Reduce unit flat price by 10
$threshold2 = 3; // Change price if items > 2
$discount2 = 20; // Reduce unit flat price by 20
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $product_in_cart === $product_id && $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 ) {
$price = round( $cart_item['data']->get_price() - $discount1, 2 );
$cart_item['data']->set_price( $price );
} elseif ( $product_in_cart === $product_id && $cart_item['quantity'] >= $threshold2 ) {
$price = round( $cart_item['data']->get_price() - $discount2, 2 );
$cart_item['data']->set_price( $price );
}
}
}
為了使其更具動態性,我想為特定類別制定此規則,因此每次我在該類別中添加產品時,都會應用該規則。 我試着用
is_product_category ('example')
if (is_product_category () && has_term ('example', 'product_cat') return;
我沒有成功,有人可以告訴我如何創造這種條件。
您的代碼中缺少針對特定產品類別的內容。 嘗試以下操作:
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 categories and discount rules (quantity threshold and discount amount)
$categories = array('example');
$threshold1 = 2; // Change price if items > 1
$discount1 = 10; // Reduce unit flat price by 10
$threshold2 = 3; // Change price if items > 2
$discount2 = 20; // Reduce unit flat price by 20
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Target specific product category(ies)
if ( has_term ($categories, 'product_cat', $cart_item['product_id']) ) {
if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 ) {
$price = round( $cart_item['data']->get_price() - $discount1, 2 );
$cart_item['data']->set_price( $price );
} elseif ( $cart_item['quantity'] >= $threshold2 ) {
$price = round( $cart_item['data']->get_price() - $discount2, 2 );
$cart_item['data']->set_price( $price );
}
}
}
}
代碼進入活動子主題(或活動主題)的functions.php文件。 測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.