如果使用我的优惠券类型,我将尝试折扣购物车中最便宜的商品:
add_filter('woocommerce_coupon_get_discount_amount', 'wc_cpn_disc', 10, 5);
function wc_cpn_disc($discount, $discounting_amount, $cart_item, $single, $coupon) {
// IF TYPE MATCHES PERFORM CUSTOM CALCULATION
if ($coupon->type == 'cheapest_free'){
global $woocommerce;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$product_price[] = get_option('woocommerce_tax_display_cart') == 'excl' ? $_product->get_price_excluding_tax() : $_product->get_price_including_tax(); /*Store all product price from cart items in Array */
}
$lowestprice = min($product_price);
$discount = number_format((float)$lowestprice/10,2,'.','');
}
return $discount;
}
折扣金额非常奇怪-无论我怎么尝试,它都不会达到我期望的价值。起初我以为这是一个百分比折扣,但我希望这是一个固定的数额。我试着在网站的其他地方运行我的“获取最低价格”功能,当最低值项为11.95时,它返回1.195,所以我知道该部分工作正常。但是265.60的总折扣是23.90——我就是不明白!
我只想在购物车里买到最低价的商品,并打折。
在博斯曼和其他几个线程的帮助下,我成功地解决了这个问题。事实证明,我需要更改我的方法-下面是完整的代码。
add_filter('woocommerce_coupon_get_discount_amount', 'tfcc_cheapest_free', 10, 5);
function tfcc_cheapest_free($discount, $discounting_amount, $cart_item, $single, $coupon) {
// IF TYPE MATCHES PERFORM CUSTOM CALCULATION
if ($coupon->type == 'cheapest_free'){
$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)/$cart_item['quantity']; // return the lowest item price as a discount
}
} else {
return 0;
}
}
}
我希望这能帮助将来需要类似功能的人。