我为我的所有woocommerce产品设置了20%的全球折扣。 我需要创建一个购物车百分比优惠券,该优惠券将应用于正常产品价格,而不是20%的折扣价。
我找到了以下代码:
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;
}
但是,它似乎仅适用于购物车中的可变产品。如何将其更改为与购物车中的可变产品和简单产品一起使用? 谢谢。
答案 0 :(得分:0)
您的代码确实过时了,有一些错误和错误。我已经更新了代码并进行了更改,以使其适用于所有产品类型:
add_filter('woocommerce_coupon_get_discount_amount', 'filter_coupon_discount_amount', 10, 5 );
function filter_coupon_discount_amount( $discount, $discounting_amount, $cart_item, $single, $coupon ) {
if ( $coupon->is_type('percent_product') || $coupon->is_type('percent') ) {
$cart_total = 0;
foreach ( WC()->cart->get_cart() as $cart_item ) {
$product = $cart_item['data'];
$cart_total += $product->get_regular_price() * $cart_item['quantity'];
}
if( $cart_total > 0 )
$discount = round( ( $cart_total / 100 ) * $coupon->get_amount(), WC()->cart->dp );
}
return $discount;
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试和工作。