仅对缺货产品应用 discount/coupon
Apply discount/coupon ONLY for backordered products
我正在尝试为延期交货的商品添加折扣代码,我在这里找到了这个,它适用于所有商品,而不仅仅是延期交货的商品,我该如何解决这个问题?提前致谢!
add_filter( 'woocommerce_coupon_is_valid', 'specific_coupons_valid_for_backorders', 10, 3 );
function specific_coupons_valid_for_backorders( $is_valid, $coupon, $discount ){
// HERE below define in the array your coupon codes
$coupon_codes = array( 'beauty' );
if( in_array( $coupon->get_code(), $coupon_codes ) ) {
$is_valid = false;
// Loop through cart items and check for backordered items
foreach ( WC()->cart->get_cart() as $cart_item ) {
if( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
$is_valid = true; // Backorder found, coupon is valid
break; // Stop and exit from the loop
}
}
}
return $is_valid;
}
WC_Discounts
class 设置购物车项目,因此在函数内循环遍历购物车项目是行不通的。您可以使用另一个过滤器 woocommerce_coupon_get_items_to_validate
来设置项目。作为一种更简单的解决方案,您可以使用此 并在商品未延期交货时将折扣应用为零。
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 );
我正在尝试为延期交货的商品添加折扣代码,我在这里找到了这个,它适用于所有商品,而不仅仅是延期交货的商品,我该如何解决这个问题?提前致谢!
add_filter( 'woocommerce_coupon_is_valid', 'specific_coupons_valid_for_backorders', 10, 3 );
function specific_coupons_valid_for_backorders( $is_valid, $coupon, $discount ){
// HERE below define in the array your coupon codes
$coupon_codes = array( 'beauty' );
if( in_array( $coupon->get_code(), $coupon_codes ) ) {
$is_valid = false;
// Loop through cart items and check for backordered items
foreach ( WC()->cart->get_cart() as $cart_item ) {
if( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
$is_valid = true; // Backorder found, coupon is valid
break; // Stop and exit from the loop
}
}
}
return $is_valid;
}
WC_Discounts
class 设置购物车项目,因此在函数内循环遍历购物车项目是行不通的。您可以使用另一个过滤器 woocommerce_coupon_get_items_to_validate
来设置项目。作为一种更简单的解决方案,您可以使用此
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 );