如果产品数量和数量大于1,我需要为每个产品增加$ 5折扣。这是我的代码。当我先在购物车中添加第二个项目时,它工作正常。但是,如果购物车中只有1个产品并且数量是2,则折扣不应适用于第一个数量,而应适用于第二个数量。
add_filter( 'woocommerce_before_calculate_totals', 'discount_on_cart_item', 10, 1 );
function discount_on_cart_item( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$count = 0;
$discount = 5;
$discount_appl = false;
//$count = WC()->cart->get_cart_contents_count();
foreach ( $cart_object->get_cart() as $cart_item ) {
$count++;
//echo $cart_item['quantity'];
if( ($count == 1 && $cart_item['quantity'] > 1 ) || ($count > 1)){
$price = $cart_item['data']->get_price(); // product price
//$discounted_price = $price - ($price * $discount); // calculation
$discounted_price = $price - $discount; // calculation
// Set the new price
$cart_item['data']->set_price( $discounted_price );
// break; // stop the loop
$discount_appl = true;
}
}
if ( $discount_appl && is_cart())
wc_add_notice( __( 'A quantity discount has been applied', 'my_theme_slug' ), 'success' );
}