我创建了一个'BOGOF'(买一送一)优惠券,使用正常的 woocommerce 优惠券方法。
该优惠券为用户提供购物车中其他 1 件商品 100% 的折扣。
优惠券设置
General:
折扣类型:百分比折扣优惠券
amount: 100
使用限制:
使用时:
- 优惠券 100% 适用于random购物车中的商品(我猜是默认行为)
Desired:
- 它需要 100% 折扣cheapest购物车中的商品。
通过以下代码,我尝试实现我的目标,不幸的是没有达到预期的结果
function filter_woocommerce_coupon_get_discount_amount( $discount, $discounting_amount, $cart_item, $single, $instance ) {
$price_array = array();
foreach( $cart_item as $item ) {
echo $item->price;
if($item->price > 0){
array_push($price_array, $item->price);
}
}
$lowestPrice = min($price_array);
if( $lowestPrice < $discount ){
$discount = $lowestPrice;
}
return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );
首先,您的代码中有一个很大的错误$cart_item
变量钩子参数是当前购物车商品,但不是购物车商品数组...
以下将对最便宜的购物车商品应用 100% 的优惠券折扣(注释代码):
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_wc_coupon_get_discount_amount', 10, 5 );
function filter_wc_coupon_get_discount_amount( $discount_amount, $discounting_amount, $cart_item, $single, $coupon ) {
// Define below your existing coupon code
$coupon_code = 'BOGOF';
// Only for a defined coupon code
if( strtolower( $coupon_code ) !== $coupon->get_code() )
return $discount_amount;
$items_prices = [];
$items_count = 0;
// Loop through cart items
foreach( WC()->cart->get_cart() as $key => $item ){
// Get the cart item price (the product price)
if ( wc_prices_include_tax() ) {
$price = wc_get_price_including_tax( $item['data'] );
} else {
$price = wc_get_price_excluding_tax( $item['data'] );
}
if ( $price > 0 ){
$items_prices[$key] = $price;
$items_count += $item['quantity'];
}
}
// Only when there is more than one item in cart
if ( $items_count > 1 ) {
asort($items_prices); // Sorting prices from lowest to highest
$item_keys = array_keys($items_prices);
$item_key = reset($item_keys); // Get current cart item key
// Targeting only the current cart item that has the lowest price
if ( $cart_item['key'] == $item_key ) {
return reset($items_prices); // return the lowest item price as a discount
}
} else {
return 0;
}
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)