首页 > 解决方案 > 不要在 WooCommerce 中对缺货产品应用优惠券折扣

问题描述

我正在尝试仅对有货的产品应用优惠券。

因此,如果我在购物车中有 5 件商品,并且有 4 件库存,那么只有 4 件将应用折扣,延期交货的产品将不会。

实际上我正在尝试更改“ ”文件get_items_to_apply_coupon中的默认“”功能。class-wc-discounts.php

我尝试计算 foreach cicle 中当前产品的库存数量,然后我将其更改为$item_to_apply->quantity库存产品和购物车产品之间的差异。

但是,如果我在 $->quantity 中输入“200”,折扣也不会改变

protected function get_items_to_apply_coupon( $coupon ) {
    $items_to_apply = array();

    foreach ( $this->get_items_to_validate() as $item ) {
        $item_to_apply = clone $item; // Clone the item so changes to this item do not affect the originals.

        if ( 0 === $this->get_discounted_price_in_cents( $item_to_apply ) || 0 >= $item_to_apply->quantity ) {
            continue;
        }

        if ( ! $coupon->is_valid_for_product( $item_to_apply->product, $item_to_apply->object ) && ! $coupon->is_valid_for_cart() ) {
            continue;
        }
        
            $items_to_apply[] = $item_to_apply;
        

    }



    return $items_to_apply;
}

标签: phpwordpresswoocommerceproductcoupon

解决方案


class-wc-discounts.php包含_

在这个函数中,我们找到了woocommerce_coupon_get_discount_amount过滤器钩子。

因此,当产品延期交货时,您可以返回 0 作为折扣

function filter_woocommerce_coupon_get_discount_amount( $discount, $price_to_discount , $cart_item, $single, $coupon ) {    
    // On backorder
    if ( $cart_item['data']->is_on_backorder() ) {
        $discount = 0;
    }

    return $discount;
}
add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );

推荐阅读