php - Woocommerce:如何在购物车中只允许一种产品类型?
问题描述
我有两种产品类型,一种是简单产品$cart_item['default-engraving']
,另一种是信用产品$cart_item['default-engraving'] && $cart_item['iconic-engraving']
。我正在尝试找到一个解决方案,如果我将简单的产品添加到购物车,则不应添加信用产品。或者,如果我将信用产品添加到购物车,则不应添加简单产品。但如果我愿意,我可以根据需要添加相同的类型,例如简单的产品类型。
解决方案
更新:无法检测添加到购物车事件的自定义购物车项目数据。
检查购物车项目将允许您防止购物车项目同时$cart_item['default-engraving']
具有$cart_item['iconic-engraving']
:
add_action( 'woocommerce_check_cart_items', 'check_cart_items_custom_data' );
function check_cart_items_custom_data() {
// Initializing: set the current product type in an array
$types = [];
// Loop through cart items
foreach (WC()->cart->get_cart() as $item ){
if( isset( $item['default-engraving'] ) )
$types[] = 'default';
if( isset( $item['iconic-engraving'] ) )
$types[] = 'iconic';
}
$types = array_unique( $types );
// Check the number of product types allowing only one
if( count( $types ) > 1 ){
// Displaying a custom notice and avoid checkout
wc_add_notice( __('Only items from one product type are allowed in cart'), 'error' );
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
原始答案:(它不适用于您的情况,因为在添加到购物车事件中无法检测到)
这是针对产品类型以仅允许购物车中的一种的方式:
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_type_allowed', 10, 3 );
function only_one_product_type_allowed( $passed, $product_id, $quantity ) {
// Initializing: set the current product type in an array
$types = [ wc_get_product( $product_id )->get_type() ];
// Loop through cart items
foreach (WC()->cart->get_cart() as $item ){
// Set each product type in the array
$types[] = wc_get_product( $item['product_id'] )->get_type();
}
$types = array_unique( $types );
// Check the number of product types allowing only one
if( count( $types ) > 1 ){
// Displaying a custom notice
wc_add_notice( __('Only items from one product type are allowed in cart'), 'error' );
return false; // Avoid add to cart
}
return $passed;
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
推荐阅读
- python - 函数中是否有像 scatter3D 的 cmp(colormaps) 这样的参数:pd.plotting.scatter_matrix?
- excel - 如何在没有 VBA 的情况下验证同一单元格(时间戳)中的日期和时间
- html - PrimeNG 11 TieredMenu 在图像上的位置
- azure - “主机名”从 Composer 发布 Azure Bot
- python - 如何打开图像以将其放入使用 tkinter 的游戏中?
- javascript - 通过 React 中的输入过滤来自 API 的数据
- python - 重构一系列嵌套的 try except 块
- r - 清理包含字符的数据集,其中的字符应该只是数字。如何对这些行进行子集化?我不想失去他们
- game-maker - gamemaker studio 2 中的 http_request 问题
- javascript - Safari中相对父元素中绝对元素的转换问题