Woocommerce 中基于产品类别的第二个项目的数量折扣
Quantity Discount for 2nd Item Based on Product Category in Woocommerce
基于 "" 对我之前的一个问题的回答代码,我想获得有关如何为 has_term()
添加 if 语句的帮助这样,使此代码仅适用于一个或多个类别。
我们将不胜感激。
以下将使用 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 文件。已测试并有效。
基于 "has_term()
添加 if 语句的帮助这样,使此代码仅适用于一个或多个类别。
我们将不胜感激。
以下将使用 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 文件。已测试并有效。