如果购买的商品处于缺货状态,则 WooCommerce 的最低订购量

时间:2020-12-21 10:11:34

标签: php wordpress woocommerce product cart

我正在使用 Woocommerce set minimum order for a specific user role 答案代码,它就像一个魅力!

不过,如果放入购物车的产品没有库存(缺货),我只希望有最低订单金额。如果购物车中的产品有库存,则不应设置最低订购量。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

要使代码仅在有缺货商品时才起作用,您需要在代码中包含对缺货商品的检查,如下所示:

add_action( 'woocommerce_check_cart_items', 'set_min_total_per_user_role' );
function set_min_total_per_user_role() {
    // Only run in the Cart or Checkout pages
    if( is_cart() || is_checkout() ) {

        // Set minimum cart total (by user role)
        $minimum_cart_total = current_user_can('company') ? 250 : 100;

        // Total (before taxes and shipping charges)
        $total = WC()->cart->subtotal;
        
        $has_backordered_items = false;
        
        // Check for backordered cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            if ( $cart_item['data']->is_on_backorder( $cart_item['quantity'] ) ) {
                $has_backordered_items = true;
                break; // stop the loop
            }
        }

        // Add an error notice is cart total is less than the minimum required
        if( $has_backordered_items && $total <= $minimum_cart_total  ) {
            // Display our error message
            wc_add_notice( sprintf( '<strong>Dear customer, minimum order of %s is required to make a purchase on your site.</strong> <br>
                Your actual cart amount is: %s',
                wc_price($minimum_cart_total),
                wc_price($total)
            ), 'error' );
        }
    }
}

代码位于活动子主题(或活动主题)的functions.php 文件中。它应该有效。

基于:Woocommerce set minimum order for a specific user role