簡體   English   中英

為特定WooCommerce產品類別的購物車項目設置最小數量

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

在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
        }
    }
}

它不起作用,因為我為特定產品類別中的第一個購物車項目設置了最小數量,但沒有為該特定產品類別中的所有項目全局設置最小數量。 任何幫助表示贊賞。

在此處輸入圖片說明

您需要首先計算目標產品類別中的項目數量…然后,當項目數量低於所定義的最小值時,您將顯示錯誤通知:

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文件中。 經過測試和工作。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM