Search code examples
phpwoocommercehook-woocommercecoupondiscount

Apply discount/coupon ONLY for backordered products


I'm trying to add a discount code just for backordered items, I found this one on here and it works for ALL items, not just backordered items, how can I fix this? Thanks in advance!

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;
}

Solution

  • The WC_Discounts class sets the cart items, so looping through the cart items within the function isn't going to work. There's another filter woocommerce_coupon_get_items_to_validate that you can use to set the items. As an easier solution you could use this answer and apply the discount as zero if the item isn't on backorder.

        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 );