【发布时间】:2020-08-18 13:54:07
【问题描述】:
我在 stackoverflow 上找到了这段代码,它可以满足我的需要,除了我需要在购物车中添加 2 个产品后立即为每个产品应用 -5 欧元的折扣。
例子:
- 对于购物车中的 1 件产品,用户将获得 0 欧元的折扣
- 对于购物车中的 2 件产品,用户将获得 5 欧元的折扣
- 对于购物车中的 3 件产品,用户将获得 10 欧元的折扣
- 对于购物车中的 4 件产品,用户将获得 15 欧元的折扣
- 对于购物车中的 5 件产品,用户将获得 20 欧元的折扣
等等……
add_action('woocommerce_cart_calculate_fees' , 'custom_discount', 10, 1);
function custom_discount( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) && ! is_user_logged_in() )
// if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only when there is 2 or more items in cart
if( $cart->get_cart_contents_count() >= 2):
// Initialising variable
$is_on_sale = false;
// Iterating through each item in cart
foreach( $cart->get_cart() as $cart_item ){
// Getting an instance of the product object
$product = $cart_item['data'];
// If a cart item is on sale, $is_on_sale is true and we stop the loop
if($product->is_on_sale()){
$is_on_sale = true;
break;
}
}
## Discount calculation ##
// fixed reduction price
$reduction = 5;
## Applied discount (no products on sale) ##
if(!$is_on_sale )
$cart->add_fee( '-5€ à partir du 2ème article commandé', -$reduction);
endif;
}
感谢任何帮助。
【问题讨论】:
标签: php wordpress woocommerce cart discount