为特定 WooCommerce 产品类别的购物车商品设置最低数量

Set a minimum quantity for cart items from specific WooCommerce product category

在 WooCommerce 中,我试图为特定产品类别的购物车商品设置最低数量。

基于“”,这是我的代码尝试:

add_action( 'woocommerce_check_cart_items', 'wc_min_item_required_qty' );
function wc_min_item_required_qty() {
    $category      = 'games'; // The targeted product category
    $min_item_qty  = 4; // Minimum Qty required (for each item)
    $display_error = false; // Initializing

    // Loop through cart items
    foreach(WC()->cart->get_cart() as $cart_item ) {
        $item_quantity = $cart_item['quantity']; // Cart item quantity
        $product_id    = $cart_item['product_id']; // The product ID

        // For cart items remaining to "Noten" producct category
        if( has_term( $category, 'product_cat', $product_id ) && $item_quantity < $min_item_qty ) {
            wc_clear_notices(); // Clear all other notices

            // Add an error notice (and avoid checkout).
            wc_add_notice( sprintf( 'You should at least pick', $min_item_qty ,'products  for'  ,$category,  'category' ), 'error' );
            break; // Stop the loop
        }
    }
}

它没有像我希望的那样工作,因为为特定产品类别的第一个购物车项目设置了最低数量,但不是全局为该类别的所有项目具体产品类别。感谢任何帮助。

您需要先计算目标产品类别中的商品数量……然后当商品数量低于定义的最小数量时,您可以显示错误通知:

add_action( 'woocommerce_check_cart_items', 'wc_min_item_required_qty' );
function wc_min_item_required_qty() {
    $category  = 'Games'; // The targeted product category
    $min_qty   = 4; // Minimum Qty required (for each item)
    $qty_count = 0; // Initializing

    // Loop through cart items
    foreach(WC()->cart->get_cart() as $item ) {
        // Count items from the targeted product category
        if( has_term( $category, 'product_cat', $item['product_id'] ) ) {
            $qty_count += $item['quantity'];
        }
    }

    // Display error notice avoiding checkout
    if( $qty_count != 0 && $qty_count < $min_qty ) {
        wc_clear_notices(); // Clear all other notices

        // Add an error notice (and avoid checkout).
        wc_add_notice( sprintf(
            __("You should pick at least %s items from %s category.", "woocommerce"),
            '<strong>' . $min_qty . '</strong>',
            '<strong>' . $category . '</strong>'
        ), 'error' );
    }
}

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