允许在Woocommerce中为特定产品类别添加到购物车最多3个产品 [英] Allow add to cart 3 products max for a specific product category in Woocommerce
问题描述
我正尝试向客户免费提供最多3个免费样品.
I am trying to send out a maximum of 3 free samples to customers with free shipping.
我创建了一些定价为0的产品,并将其设置为样品"产品类别.
I have created some 0 priced product and set them in "samples" product category.
此特定产品具有单独出售"的选项,因此客户只能在每个样本中拥有一个.
This specific products have option "sold individually" so customers can only have one of each sample.
我无法弄清楚如何最多只允许购物车中此产品类别中的3个样品产品.
I cannot figure out how to allow only a maximum of 3 samples products from this product category on cart.
感谢您的帮助.
推荐答案
使用 woocommerce_add_to_cart_validation
操作挂钩可以轻松完成此操作,以将样品"产品类别中的客户限制为最多3个项目,这方式:
This can be done easily using woocommerce_add_to_cart_validation
action hook to limit customers to a maximum of 3 items from "sample" product category, this way:
add_action('woocommerce_add_to_cart_validation', 'max_3_items_for_samples', 20, 3 );
function max_3_items_for_samples( $passed, $product_id, $quantity ) {
// HERE define your product category ID, slug or name.
$category = 'clothing';
$limit = 3; // HERE set your limit
$count = 0;
// Loop through cart items checking for specific product categories
foreach ( WC()->cart->get_cart() as $cat_item ) {
if( has_term( $category, 'product_cat', $cat_item['product_id'] ) )
$count++;
}
if( has_term( $category, 'product_cat', $product_id ) && $count == $limit )
$count++;
// Total item count for the defined product category is more than 3
if( $count > $limit ){
// HERE set the text for the custom notice
$notice = __('Sorry, you can not add to cart more than 3 free samples.', 'woocommerce');
// Display a custom notice
wc_add_notice( $notice, 'error' );
// Avoid adding to cart
$passed = false;
}
return $passed;
}
代码进入活动的子主题(或主题)的function.php文件中.
经过测试,可以正常工作.
Tested and works.
这篇关于允许在Woocommerce中为特定产品类别添加到购物车最多3个产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!