在WooCommerce中,我试图为特定产品类别中的购物车商品设置最小数量。
基于“ Minimum cart item quantity for a specific product category in 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
}
}
}
它不起作用,因为我为特定产品类别中的第一个购物车商品设置了最低数量,但是对于该特定产品类别中的所有商品均未设置全局最低数量。任何帮助表示赞赏。
答案 0 :(得分:2)
您需要首先计算目标产品类别中的项目数...然后,当项目数低于定义的最小值时,您将显示错误通知:
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文件中。经过测试,可以正常工作。