如何为每件商品和每天的 WooCommerce 订单设置最大限制

How to set a maximum limit in WooCommerce orders per item & per day

我想在我的商店中每天对每种产品只允许特定数量的订单。知道我必须添加哪个挂钩吗?

谢谢

下面的代码使用产品 ID 获取当天的总数量。如果这大于或等于您设置的 $dailyOrderLimit(在我的示例中为 10),则无法购买该产品。

add_filter('woocommerce_is_purchasable', 'preventPurchaseIfDailyOrderLimitReached', 10, 2);

function preventPurchaseIfDailyOrderLimitReached($is_purchasable, $product)
{
    $dailyOrderLimit = 10;
    $productId = $product->get_id();
    $quantityOrderedToday = getDailyOrderAmount($productId);

    if ($quantityOrderedToday >= $dailyOrderLimit) {
        $is_purchasable = false;
    }

    return $is_purchasable;
}

function getDailyOrderAmount($productId)
{
    global $wpdb;
    $today = date('Y-m-d');
    $result = $wpdb->get_results("SELECT sum(product_qty) as quantity_ordered_today FROM {$wpdb->prefix}wc_order_product_lookup where product_id= {$productId} and date_created > '{$today} 00:00:00';");

    return $result[0]->quantity_ordered_today;
}

代码已经过测试并且可以工作。将其添加到子主题的 functions.php 文件中。

如果您觉得我的回答对您有帮助,您可以accept my answer