在购物车商品库存问题上禁用 WooCommerce 下订单结帐按钮

On cart items stock issue disable WooCommerce Place order checkout button

目前,如果某件商品缺货,结账页面会显示一条消息:

Sorry, we do not have enough "xxx" in stock to fulfil your order (2 available). We apologise for any inconvenience caused.

因此,如果出现该消息,那么我想通过简单地删除它来禁用页面上的“继续结帐”按钮。

如果没有出现该消息,则显示“继续结帐”按钮。

显然我会创建一个 IF 语句,如果为真则显示,否则不显示等。

这是我的“继续结帐”按钮代码:

<input type="submit" name="cart_submit" class="checkout-button button alt wc-forward" style="text-transform: capitalize;" value="<?php esc_html_e( 'Proceed to checkout', 'woocommerce' ); ?>" />

那么我可以在 Woocommerce 中调用一种方法来查看是否调用了该错误消息?

我尝试扫描整个网页以查找该消息,如果为真,则执行 xyz 但这不起作用(可能是会话)。

如有任何帮助,我们将不胜感激。

Woocommerce 具有使用 global $product 获得 product 值的特殊功能。 您可以使用以下代码访问您的产品库存数量。

global $product;
$quantity = $product->get_stock_quantity();
if($quantity < 1){
  //take decision. 
}

基于 WC_Cart check_cart_item_stock() method source code,显示您问题的错误代码,第一个函数将检查购物车商品库存作为条件函数,如果一切正常则返回 true,如果显示错误则返回 false购物车商品存在库存问题。

如果购物车商品有库存问题,第二个功能将显示禁用的灰色“下订单”按钮。

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

在结帐页面上禁用灰色的“下订单”按钮

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。


如果您想删除结帐“下订单”按钮,请替换为:

return '<a class="button alt disabled" style="cursor:not-allowed; text-align:center">' .__('Place order', 'woocommerce') . '</a>';

与:

return '';

相关: