在WooCommerce中,我会自动应用优惠券,但我无法找到解决此问题的方法:
例如:
我使用$ wc-> cart-> add_discount($ discount),但它返回"优惠券已经应用"因为第二组物品在购物车中。
你知道这是否可能吗?
由于
答案 0 :(得分:1)
您应该更好地使用自定义折扣功能来实现此功能,而不是使用优惠券:
add_action( 'woocommerce_cart_calculate_fees', 'cart_item_discount_by3', 10, 1 );
function cart_item_discount_by3( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// initializing and set variables
$discount = 0;
$by3 = 3; // each 3 item quantity
$dicount_price_by3 = 5; // amout to discount each 3 items quantity
// Iterating through each cart item
foreach( $cart_object->get_cart() as $cart_item ):
// Get the item quantity
$qty = $cart_item["quantity"];
// starting when quantity is upto 3
if($qty >= $by3):
for($j = $by3, $k = 0; $j <= $qty; $j+=$by3, $k++);
$discount += $dicount_price_by3 * $k;
break;
endif;
endforeach;
// Adding the discount (a negative fee)
if ($discount > 0){
$cart_object->add_fee( __( "Discount quantity", 'woocommerce'), -$discount, true );
# Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false)
// Displaying a custom notice (optional)
wc_clear_notices();
wc_add_notice( __("You get a quantity discount on some items"), 'notice');
}
}
代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。
此代码经过测试并有效。