我在我的Wordpress / Woocommerce网站上测试了此代码
add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation_callback', 10, 3 );
function add_to_cart_validation_callback( $passed, $product_id, $quantity) {
// HERE set your alert text message
$message = __( 'ohoh dit gaat niet', 'woocommerce' );
if( ! WC()->cart->is_empty() ) {
// Get the product category terms for the current product
$terms_slugs = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'slugs'));
// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item ){
if( has_term( $terms_slugs, 'product_cat', $cart_item['product_id'] )) {
$passed = false;
wc_add_notice( $message, 'error' );
break;
}
}
}
return $passed;
}
使用此代码,您只能从一个类别中购买商品。我正在寻找其他类似的东西
我有4个类别 -主页 -花园 -服装 -玩具
如果用户将玩具中的产品放入购物车,他将无法购买其他类别的商品。
但是,如果用户将产品从Garden放入购物车,他可以将其与Home和Outfit类别组合。
概述:用户可以将产品组合到家居,花园和服装中,而不能与玩具组合。