我想根据购物车中的商品数量获得有条件累进折扣,将 2 个产品添加到购物车后,您将获得折扣,您添加的更多产品和更多折扣。
例如:
> 1 个产品 – 全价(无折扣)
> 2 种产品 – 全价,合并价格 10%折扣
> 3 种产品 – 全价,总价格折扣 15%
> 4 种产品 – 全价,合并价格 20%折扣
>依此类推……
我在互联网上搜索没有任何成功.在搜索折扣时,我只是依靠 WooCommerce 优惠券功能,或者我得到了一些旧的错误代码……
/* The calculation:
* — The count => Based on quantity by item and total of items in cart
* — The percent is 0.05 (5%) and it grows with each additional item (as you asked)
* — I add the subtotal of each item line to get the total sum…
*/
function cart_progressive_discount() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$cart_count = 0;
$cart_lines_total = 0;
foreach(WC()->cart->get_cart() as $item_key => $cart_item){
// Adds the quantity of each item to the count
$cart_count = $cart_count + $cart_item["quantity"];
// Adds The items subtotal to total
$cart_lines_total += $cart_item["line_total"];
}
// percent is 5%
$percent = -0.05;
// We fix the discount max to 50% (-0.05 * 10)
$cart_count_max = 10;
// Discount calculations:
$discount = $percent * $cart_count * $cart_lines_total;
$discount2 = $percent * $cart_count_max * $cart_lines_total;
$discount_text = __( 'Quantity discount', 'woocommerce' );
// For 0 or 1 item
if( $cart_count < 2 ) {
return;
}
// Between 2 and 9 items, progressive incremental discount based on item quantity (From 10% to 45%)
elseif( $cart_count > 1 && $cart_count < 10) {
WC()->cart->add_fee( $discount_text, $discount, false );
}
// Up to 9 items (Fixed discount at 50%)
else {
WC()->cart->add_fee( $discount_text, $discount2, false );
}
}
add_action( 'woocommerce_cart_calculate_fees','cart_progressive_discount' );
当然这可以在您的活动子主题(或主题)的 function.php 文件中,也可以在任何插件文件中,此代码经过测试并可以使用。
专业提供WordPress主题安装、深度汉化、加速优化等各类网站建设服务,详询在线客服!