php - WooCommerce 为购物车上最便宜的商品增加 50% 的折扣,买一送一 50% 的折扣,买二送二 50% 的折扣
问题描述
我想给用户买一个买另一个50%的折扣,我的概念是有一张优惠券和:
条件 1) 如果用户将两件商品添加到购物车中,价格最低的商品将获得 50% 的折扣。(我已经实现了,代码如下)
条件 2) 如果用户将三件商品添加到购物车中,价格最低的商品将获得 50% 的折扣。(与第一条规则相同,我已经做到了。)
条件 3) 如果用户在购物车中添加了四件商品,则最低价商品 + 第二价商品各获得 50% 的折扣。(请帮忙)
条件 4) 如果用户将六件商品添加到购物车中,则最低三件商品将获得 50% 的折扣。(需要帮忙)
代码 :
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 ) {
//Already created coupon code for which this code is to be executed.
$coupon_code = 'test50';
// Only when $coupon_code is used
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 ((($price)/100)*50); // return the lowest item price as a discount
}
} else {
return 0;
}
}
解决方案
推荐阅读
- xamarin.forms - 如何从 web api 分页列表视图分页同步融合中获取 xamarin 表单的 json 数据?
- django - DJANGO
- ruby-on-rails - 如何检查记录是否分页/将分页?
- excel - 为什么我的 For 循环在最后一行之前退出?
- php - 尝试使用 PHP 将数据库中的图像插入到每个条目上方的新闻博客中
- android - 从 PC 到 Android 模拟器的套接字连接
- mysql - 收到太多 MySQL 查询请求时,Lambda 函数“错误:连接 ETIMEDOUT”
- gcc - 在 dev-C++ 中使用 scanf_s 会出现错误:“scanf_s”未在此范围内声明
- search - 在网格中为动态列制作过滤器
- javascript - 没有在简单的代码中得到正确的输出