MainWP Community

Disable Place Order on Checkout for out of stock products in the cart in WooCommerce

Disable Place Order on Checkout for out of stock products in the cart in WooCommerce on your child site.

Snippet Type

Execute on Child Sites

Snippet

function wc_check_cart_item_stock() {
    $product_qty_in_cart      = WC()->cart->get_cart_item_quantities();
    $current_session_order_id = isset( WC()->session->order_awaiting_payment ) ? absint( WC()->session->order_awaiting_payment ) : 0;

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $product = $values['data'];

        // Check stock based on stock-status.
        if ( ! $product->is_in_stock() ) {
            return false;
        }

        // We only need to check products managing stock, with a limited stock qty.
        if ( ! $product->managing_stock() || $product->backorders_allowed() ) {
            continue;
        }

        // Check stock based on all items in the cart and consider any held stock within pending orders.
        $held_stock     = wc_get_held_stock_quantity( $product, $current_session_order_id );
        $required_stock = $product_qty_in_cart[ $product->get_stock_managed_by_id() ];

        if ( $product->get_stock_quantity() < ( $held_stock + $required_stock ) ) {
            return false;
        }
    }
    return true;
}

add_filter( 'woocommerce_order_button_html', 'disable_order_button_html' );
function disable_order_button_html( $button ) {
    if( wc_check_cart_item_stock() ) {
        return $button;
    } else {
        return '<a class="button alt disabled" style="cursor:not-allowed; text-align:center">' .__('Place order', 'woocommerce') . '</a>';
    }
}
1 Like