【问题标题】:Woocommerce discount on second item when not on sale items are in cart购物车中未销售商品时,第二件商品的 Woocommerce 折扣
【发布时间】:2018-12-25 18:03:50
【问题描述】:
【问题讨论】:
标签:
php
wordpress
woocommerce
cart
discount
【解决方案1】:
当购物车中没有在售商品时,以下将在第 2 件商品上享受 10% 的折扣:
add_action('woocommerce_cart_calculate_fees' , 'custom_2nd_item_discount', 10, 1);
function custom_2nd_item_discount( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Only for 2 items or more
if ( $cart->get_cart_contents_count() < 2 )
return;
// Initialising variable
$has_on_sale = false;
$count_items = $discount = 0;
$percentage = 10; // 10 %
// Iterating through each item in cart
foreach( $cart->get_cart() as $cart_item ){
$count_items++;
if( $cart_item['data']->is_on_sale() ){
$has_on_sale = true;
}
if( 2 == $count_items ){
$discount = wc_get_price_excluding_tax( $cart_item['data'] ) * $percentage / 100;
}
}
// Apply discount to 2nd item for non on sale items in cart
if( ! $has_on_sale && $discount > 0 )
$cart->add_fee( sprintf( __("2nd item %s%% Discount"), $percentage), -$discount );
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。