php - 在 Woocommerce 中一次只允许购物车中的一个产品类别
问题描述
我将如何配置 Woocommerce 购物车以一次只允许一种产品类别类型?
解决方案
以下代码将允许仅将来自一个产品类别的商品添加到购物车,从而避免添加到购物车并显示自定义通知:
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_category_allowed', 20, 3 );
function only_one_product_category_allowed( $passed, $product_id, $quantity) {
// Getting the product categories term slugs in an array for the current product
$term_slugs = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'slugs') );
// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){
// Check if the product category of the current product don't match with a cart item
if( ! has_term( $term_slugs, 'product_cat', $cart_item['product_id'] ) ){
// Displaying a custom notice
wc_add_notice( __('Only items from one product category are allowed in cart'), 'error' );
// Avoid add to cart
return false; // exit
}
}
return $passed;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。测试和工作。
添加(更新) - 相同但仅适用于父产品类别:
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_category_allowed', 20, 3 );
function only_one_product_category_allowed( $passed, $product_id, $quantity) {
$parent_term_ids = $item_parent_term_ids = array(); // Initializing
// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, 'product_cat' ) as $term ){
if( $term->parent > 0 ){
$parent_term_ids[] = $term->parent; // Set the parent product category
}
}
// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){
// Loop through the cart item product category terms to get only parent main category term
foreach( get_the_terms( $cart_item['product_id'], 'product_cat' ) as $term ){
if( $term->parent > 0 ){
$item_parent_term_ids[] = $term->parent; // Set the parent product category
}
}
// Check if parent product categories don't match
if( ! array_intersect( $parent_term_ids, $item_parent_term_ids ) ){
// Displaying a custom notice
wc_add_notice( __('Only items from one product category are allowed in cart'), 'error' );
// Avoid add to cart
return false; // exit
}
}
return $passed;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。测试和工作。
推荐阅读
- r - 将 Origina Destinations 的 GIS 数据重新排列为每个点一行
- c - 为什么从 arr 读取时我将所有名称放在一行中?
- postgresql - EFCore 查询以按产品搜索词获取每个供应商的产品数量
- r - CPI 与 R 的通货膨胀率
- html - 仅一个单词的字母间距不正确
- java - 确保十进制数的字符串 repr 始终为 n 个字符长
- json - 将json数组转换为scala列表
- delphi - Delphi TFontDialog - 如何针对高 Dpi 进行缩放?
- node.js - 使用查询参数处理路由别名
- node.js - 在 NODE JS 中使用 extract-zip 提取 zip 文件时如何处理错误?