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

yos*_*ber 3 php wordpress cart custom-taxonomy woocommerce

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

根据“ 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

Loi*_*tec 5

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

\n\n
add_action( \'woocommerce_check_cart_items\', \'wc_min_item_required_qty\' );\nfunction wc_min_item_required_qty() {\n    $category  = \'Games\'; // The targeted product category\n    $min_qty   = 4; // Minimum Qty required (for each item)\n    $qty_count = 0; // Initializing\n\n    // Loop through cart items\n    foreach(WC()->cart->get_cart() as $item ) {\n        // Count items from the targeted product category\n        if( has_term( $category, \'product_cat\', $item[\'product_id\'] ) ) {\n            $qty_count += $item[\'quantity\'];\n        }\n    }\n\n    // Display error notice avoiding checkout\n    if( $qty_count != 0 && $qty_count < $min_qty ) {\n        wc_clear_notices(); // Clear all other notices\n\n        // Add an error notice (and avoid checkout).\n        wc_add_notice( sprintf(\n            __("You should pick at least %s items from %s category.", "woocommerce"),\n            \'<strong>\' . $min_qty . \'</strong>\',\n            \'<strong>\' . $category . \'</strong>\'\n        ), \'error\' );\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。

\n\n

在此输入图像描述

\n