在WooCommerce中,我的产品的正常价格为X,销售价格为Y.我想添加一张代码优惠券,价格为45美元,可以从正常价格X中扣除.
我希望优惠券无视销售价格,所以我得到X- $45不是Y- $45.但是当没有使用优惠券时,使用价格Y.
我发现以下适用于百分比折扣,但我似乎无法使其适用于固定产品折扣价格.
add_filter('woocommerce_coupon_get_discount_amount', 'woocommerce_coupon_get_discount_amount', 10, 5 );
function woocommerce_coupon_get_discount_amount( $discount, $discounting_amount, $cart_item, $single, $coupon ) {
if ($coupon->type == 'percent_product' || $coupon->type == 'percent') {
global $woocommerce;
$cart_total = 0;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
$variable_product1= new WC_Product_Variation( $cart_item["variation_id"] );
$cart_total += $variable_product1 ->regular_price * $cart_item['quantity'];
}
$discount = round( ( $cart_total / 100 ) * $coupon->amount, $woocommerce->cart->dp );
return $discount;
}
return $discount;
}
解决方法:
这似乎检查优惠券,然后在应用优惠券之前将购物车价格更改为正常价格而不是折扣价格(从此应用程序中的woocommerce动态定价获得).放在functions.php中
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 10, 1);
function add_custom_price( $cart_object) {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$coupon = False;
if ($coupons = WC()->cart->get_applied_coupons() == False )
$coupon = False;
else {
foreach ( WC()->cart->get_applied_coupons() as $code ) {
$coupons1 = new WC_Coupon( $code );
if ($coupons1->type == 'percent_product' || $coupons1->type == 'percent')
$coupon = True;
}
}
if ($coupon == True)
foreach ( $cart_object->get_cart() as $cart_item )
{
$price = $cart_item['data']->regular_price;
$cart_item['data']->set_price( $price );
}
}