Woocommerce 添加到购物车产品限制为 4 个特定产品
Woocommerce Add to cart product Restriction to 4 specific products
我正在使用 woocommerce 并陷入困境。
我有 4 种不同的产品,ID 分别为 1、2、3 和 4。
我需要的是客户一次可以在购物车中添加 4 件商品中的任意一件。例如,如果商品 3 在购物车中,则无法将商品 4 或 1 或 2 添加到购物车。
我如何在 Woocommerce 中获得它?
感谢任何帮助。
更新:试试这个,它应该避免,对于定义的产品 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;
}
代码进入活动子主题(或活动主题)的 function.php 文件。
已测试并有效
我正在使用 woocommerce 并陷入困境。
我有 4 种不同的产品,ID 分别为 1、2、3 和 4。
我需要的是客户一次可以在购物车中添加 4 件商品中的任意一件。例如,如果商品 3 在购物车中,则无法将商品 4 或 1 或 2 添加到购物车。
我如何在 Woocommerce 中获得它?
感谢任何帮助。
更新:试试这个,它应该避免,对于定义的产品 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;
}
代码进入活动子主题(或活动主题)的 function.php 文件。
已测试并有效