gpt4 book ai didi

php - 对 WooCommerce 中最便宜的购物车商品应用 100% 的优惠券折扣

转载 作者:行者123 更新时间:2023-12-05 02:07:47 25 4
gpt4 key购买 nike

我使用普通的 woocommerce 优惠券方法创建了一张“BOGOF”(买一送一)优惠券。

优惠券为用户提供了购物车中其他 1 件商品的 100% 百分比折扣。


Coupon settings

General:

  • Discount type: Percentage discount Coupon

  • amount: 100

Usage limits:

  • Limit usage to X items: 1

使用时:

  • 优惠券 100% 应用于购物车中的随机商品(我猜是默认行为)

期望:

  • 它需要对购物车中最便宜的商品进行 100% 的折扣。

我尝试用下面的代码实现我的目标,不幸的是没有得到想要的结果

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 变量 Hook 参数是当前购物车商品,而不是购物车商品数组...

以下将对最便宜的购物车商品(注释代码)应用 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 文件。经过测试并有效。

关于php - 对 WooCommerce 中最便宜的购物车商品应用 100% 的优惠券折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61480164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com