[英]Quantity Discount for 2nd Item Based on Product Category in Woocommerce
基於我以前的一個問題的“ 僅在Woocommerce中僅對第二項商品有數量折扣 ”的答案代碼,我希望獲得有關如何為has_term()
添加if語句的has_term()
,這樣,使該代碼僅適用於一個或多個類別。
任何軌道將不勝感激。
以下內容將使用WordPress has_tem()
條件函數將代碼擴展為定義的產品類別:
add_action( 'woocommerce_cart_calculate_fees', 'second_item_discount', 10, 1 );
function second_item_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$percentage = 20; // 20%
$categories = array('cat1', 'cat2'); // Defined product categories term slugs
$discount = 0;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// When quantity is more than 1 and for defined product categories
if( $cart_item['quantity'] > 1 && has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
// 20% of the product price as a discount
$discount += wc_get_price_excluding_tax( $cart_item['data'] ) * $percentage / 100;
}
}
if( $discount > 0 )
$cart->add_fee( __( '2nd item discount', 'woocommerce' ) , -$discount );
}
代碼進入您的活動子主題(或活動主題)的function.php文件中。 經過測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.