mirror of
https://gh.wpcy.net/https://github.com/mainwp/Code-Snippets-Functions.git
synced 2026-05-02 12:02:25 +08:00
https://stackoverflow.com/questions/64235089/on-cart-items-stock-issue-disable-woocommerce-place-order-checkout-button/
37 lines
1.5 KiB
Text
37 lines
1.5 KiB
Text
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>';
|
|
}
|
|
}
|