0

Is it possible to allow a certain woocommerce coupon only on backorders?

I've tried to use If WooCommerce Cart items are on backorder do not apply coupon answer code that restricts backordered products from using any coupons.

I have changed if( $stock_info < 1 ){ to if( $stock_info > 0 ){ instead

But then I can only use coupons on backorders… but where do I make this work on a certain coupon?

May I use its ID? but where?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
lagalga
  • 1
  • 2

1 Answers1

0

The following code will make specific defined coupons codes valid when there is backordered items in cart:

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( 'summer', 'tenpercent' );

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

Code goes in function.php file of your active child theme (or active theme). Tested and works.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399