我已经使用 woocommerce 设置了套餐,根据所选套餐有 1,2 和 3 个免费产品。包值存储在 woocommerce 会话中。所有其他功能都完成了。我只想要一些条件,例如,如果用户选择了允许 3 个免费产品的包。那么购物车中 3 个最低价格的商品将有折扣。这是我目前编写的代码。
add_action('woocommerce_cart_calculate_fees' , 'add_user_discounts');
function add_user_discounts( WC_Cart $cart ){
global $woocommerce;
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
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);
sort($product_price);
$package_val = WC()->session->get( 'packval');
if($package_val == 17)
{
$discount = $lowestprice;
}
if($package_val == 22)
{
if(sizeof($product_price) == 1)
{
$discount = $lowestprice*2;
}
else
{
$discount = $lowestprice+$product_price[1];
}
}
if($package_val == 27)
{
if(sizeof($product_price) == 1)
{
$discount = $lowestprice*3;
}
else if(sizeof($product_price) == 2)
{
$discount = $lowestprice+$product_price[1];
}
else
{
$discount = $lowestprice+$product_price[1]+$product_price[2];
}
}
$cart->add_fee( 'discount items', -$discount);
}
对于包装价值 17,将有 1 个产品折扣,产品价格最低,效果很好。 但是对于多个产品应该有一些其他条件,例如,如果最低价格产品的数量大于 1,则第二个套餐折扣将为 $lowest*2,否则折扣将为 $lowest+$second_lowest。套餐 3 同理,优惠 3 件。