2

In Woocommerce I would like to hide Cash on Delivery payment method if any cart item is backordered, meaning if the customer add any items to cart which are allowed for backorders but have not enough stock regarding the added quantity.

My main concern is to not allow them to pay if we don't have this product at store, and if we can backorder that, we just put a desired quantity and ask for them to pay.

Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Potter91
  • 33
  • 4
  • 1
    **To the community:This question is not too broad** , even if the OP has not provided any code… see my very short code in the below answer. Thanks to consider reopening, as useful for the community. – LoicTheAztec Oct 16 '18 at 14:55

1 Answers1

3

The following code will hide "Cash On Delivery" ('cod') payment method if any cart item is backordered:

add_filter( 'woocommerce_available_payment_gateways', 'backordered_items_hide_cod', 90, 1 );
function backordered_items_hide_cod( $available_gateways ) {
    // Only on front end
    if ( is_admin() )
        return $available_gateways;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ){
        if( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
            // Hide "COD" payment gateway
            unset($available_gateways['cod']);
            break; // Stop the loop
        }
    }

    return $available_gateways;
}

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

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • the above code does not work well in latest versions of WC, throwing an error if the cart is empty, so an improvement might be adding the following check before the loop (foreach): ` if ( WC()->cart->get_cart_contents_count() == 0 ) { return $available_gateways; } ` – RwkY Dec 07 '22 at 08:39