Minimum cart item quantity for specific product categories in WooCommerce

前端 未结 2 671
醉话见心
醉话见心 2020-12-20 07:37

In WooCommerce, I need to set up a minimum quantity for each item of a product category. I searched the forum and found some code that works fine except it only counts the Q

2条回答
  •  旧巷少年郎
    2020-12-20 08:13

    To make it work for a certain product category item counts in total use this code instead:

    add_action( 'woocommerce_check_cart_items', 'wc_min_item_required_qty' );
    function wc_min_item_required_qty() {
        $categories    = '30'; // The targeted product category slug or ID
        $max_item_qty  = 10; // Minimum Qty required (for each item)
        $display_error = false; // Initializing
    
        // Loop through cart items
        foreach(WC()->cart->get_cart() as $cart_item ) {
            
            $product_id    = $cart_item['product_id']; // The product ID
            
        if( has_term( $categories, 'product_cat', $product_id )) {
            $item_quantity += $cart_item['quantity']; // Cart item quantity
        }
            // For cart items remaining to "Pizza" product category
            if( has_term( $categories, 'product_cat', $product_id ) && $item_quantity > $max_item_qty ) {
                
                wc_clear_notices(); // Clear all other notices
                
                // Add an error notice (and avoid checkout).
                wc_add_notice( sprintf( 'We can only take orders of up to 10 burgers per customer', $max_item_qty , $item_quantity ), 'error' );
                break; // Stop the loop
            }
        }
    }
    
    

提交回复
热议问题