对 WooCommerce 中最便宜的购物车商品应用 100% 优惠券折扣

Cha*_*har 4 php wordpress discount coupon woocommerce

我使用正常的 woocommerce 优惠券方法创建了一张“ BOGOF ”(买一送一)优惠券。

该优惠券为用户提供购物车中其他 1 件商品 100% 的折扣。


优惠券设置

一般的:

  • 折扣类型:百分比折扣 优惠券

  • 数量:100

使用限制:

  • 限制使用 X 项:1

使用时:

  • 优惠券 100% 适用于购物车中的随机商品(我猜是默认行为)

期望:

  • 它需要对购物车中最便宜的商品进行 100% 折扣。

通过以下代码,我尝试实现我的目标,不幸的是没有达到预期的结果

function filter_woocommerce_coupon_get_discount_amount( $discount, $discounting_amount, $cart_item, $single, $instance ) { 
    $price_array = array();

    foreach( $cart_item as $item ) {
        echo $item->price;
        if($item->price > 0){
            array_push($price_array, $item->price);
        }
    }

    $lowestPrice = min($price_array);

    if( $lowestPrice < $discount ){
        $discount = $lowestPrice; 
    }

    return $discount; 
}    
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 6

首先,您的代码中有一个很大的错误,因为$cart_item变量钩子参数是当前的购物车项目,而不是购物车项目数组......

以下将对最便宜的购物车商品应用 100% 的优惠券折扣(注释代码):

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 ) { 
    // Define below your existing coupon code
    $coupon_code = 'BOGOF';

    // Only for a defined coupon code
    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 reset($items_prices); // return the lowest item price as a discount
        }
    } else {
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。