[英]Woocommerce Add to cart product Restriction to 4 specific products
I am using woocommerce and stuck in a situation. 我正在使用woocommerce并陷入困境。
I have 4 different products with IDs 1, 2, 3 and 4. 我有ID为1、2、3和4的4种不同产品。
What I need is that customer can add any 1 of the 4 items in cart at a time. 我需要的是,客户可以一次在购物车中添加4个商品中的任何一个。 For instance, if item 3 is in the cart then item 4 or 1 or 2 cannot be added to the cart.
例如,如果项目3在购物车中,则不能将项目4或1或2添加到购物车。
How do I get this in Woocommerce? 我如何在Woocommerce中获得这个?
Any help is appreciated. 任何帮助表示赞赏。
Updated: Try this, it should avoid, for defined product Ids, adding to cart when a another targeted product already exist in cart items, displaying a custom error message: 已更新:尝试此操作,对于已定义产品ID,应避免在购物车项目中已经存在另一个目标产品时将其添加到购物车中,并显示自定义错误消息:
add_filter( 'woocommerce_add_to_cart_validation', 'conditional_product_in_cart', 10, 3 );
function conditional_product_in_cart( $passed, $product_id, $quantity) {
// HERE define your 4 specific product Ids
$products_ids = array( 37, 40, 47, 53 );
// Searching in cart for IDs
if ( ! WC()->cart->is_empty() )
foreach( WC()->cart->get_cart() as $cart_item ){
$item_pid = $cart_item['product_id'];
// If current product is from the targeted IDs and a another targeted product id in cart
if( in_array( $item_pid, $products_ids ) && in_array( $product_id, $products_ids ) && $product_id != $item_pid ){
$passed = false; // Avoid add to cart
break; // Stop the loop
}
}
if ( ! $passed ){
// Displaying a custom message
$message = __("You can only have one product in cart at the time.", "woocommerce");
wc_add_notice( $message, 'error' );
}
return $passed;
}
Code goes in function.php file of the active child theme (or active theme). 代码进入活动子主题(或活动主题)的function.php文件中。
Tested and works 经过测试和工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.