woocommerce - 防止订单混合某些类别的产品
问题描述
我试图阻止用户从某些类别中订购商品,如果他们已经从某个类别订购过。
例如,如果用户已经拥有这些类别之一的产品,但无法从该列表中的其他类别订购
- 常规的
- 大的
- 孩子们
- 健康
- 膳食生成器
但他们仍然可以从附加项目类别中订购。
我一直在看下面的内容,但是在我的情况下,购物车中的第一个项目可能来自附加项目,这些是允许的,所以我需要一个循环,但无法解决。
Woocommerce - 防止将两个不同类别的商品添加到购物车
提前致谢
解决方案
我找到了我的循环的解决方案
function get_product_top_level_category($prod_id) {
$cat = get_the_terms( $prod_id, 'product_cat' );
$return_array = array();
foreach ($cat as $category) {
if($category->parent == 0){
$return_array[] = $category->term_id;
}
}
return $return_array;
}
add_filter ( 'woocommerce_before_cart', 'restrict_cart_for_a_single_category' );
function restrict_cart_for_a_single_category() {
global $woocommerce;
$cart_contents = $woocommerce->cart->get_cart( );
$cart_item_keys = array_keys ( $cart_contents );
$cart_item_count = count ( $cart_item_keys );
// Do nothing if the cart is empty or has only one item
if ( ! $cart_contents || $cart_item_count == 1 ) {
return null;
}
// Multiple Items in cart
$categories_not_allowed_mixing = array(
'Fitness',
'Kids',
'Large',
'Meal Builder',
'Regular'
);
$categories_found = array();
// Now we check each subsequent items top-level parent category
foreach ( $cart_item_keys as $key ) {
$product_id = $cart_contents[$key]['product_id'];
$product_top_category = get_product_top_level_category( $product_id );
foreach ($product_top_category as $top_category) {
$product_top_category_term = get_term ( $top_category, 'product_cat' );
$product_top_category_name = $product_top_category_term->name;
if(in_array($product_top_category_name, $categories_not_allowed_mixing)) {
if(in_array($product_top_category_name, $categories_found)) {
// if category name is already in the array do nothing as multiples are allowed
} else {
$categories_found[] = $product_top_category_name;
// check how many of the category
}
}
if ( count($categories_found) > 1 ) {
$woocommerce->cart->set_quantity ( $key, 0, true );
$restrict_categories = 1;
}
}
}
// code to display the message or warning only once for any user
if ( isset ( $restrict_categories ) ) {
echo '<p class="woocommerce-error">You can not mix meal plans with other products, we have removed the additional items from your cart. </p>';
//add your code for redirection here
}
}
推荐阅读
- c# - 为 3D 噪声生成查找表
- java - 如果总和更大,则创建异常
- python - Tweepy API:什么是会话对象?
- java - CXF - 如何使用 CXF 3.2.6 正确配置 Spnego
- gdb - 是否可以从 gdb 修改源代码?
- reporting-services - SSRS - 记录用户对报告的操作
- javascript - 当 Electron 窗口设置为 frame: false 时,没有任何东西被聚焦
- c# - SSIS Active Directory extract getting periodic errors
- css - PRE 标记忽略换行符
- python - 用多个字典值替换字符串中的单词?