首页 > 解决方案 > 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;
    }
}

以上代码信用:对 WooCommerce 中最便宜的购物车商品应用 100% 优惠券折扣

标签: phpwordpresswoocommerce

解决方案


推荐阅读