我有3个“主”类别,环境,冷藏和冷冻。环境然后分解为3个其他类别,食品和饮料,非食品和宠物产品,每个都有自己的子类别。我尝试了以下代码,从答案中只允许从WooCommerce中相同父类别的产品添加到购物车,但它会将其限制为“非食品”例如,而不是父类别“环境”:
add_filter( 'woocommerce_add_to_cart_validation', 'avoid_add_to_cart_from_different_main_categories', 10, 3 );
function avoid_add_to_cart_from_different_main_categories( $passed, $product_id, $quantity ) {
$cart = WC()->cart;
$taxonomy = 'product_cat';
$ancestors = [];
if( $cart->is_empty() )
return $passed;
$terms = (array) wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'ids') );
if( count($terms) > 0 ) {
// Loop through product category terms set for the current product
foreach( $terms as $term) {
foreach( get_ancestors( $term, $taxonomy ) as $term_id ) {
$ancestors[(int) $term_id] = (int) $term_id;
}
}
// Loop through cart items
foreach ( $cart->get_cart() as $item ) {
$terms = (array) wp_get_post_terms( $item['product_id'], $taxonomy, array('fields' => 'ids') );
if( count($terms) > 0 ) {
// Loop through product category terms set for the current cart item
foreach( $terms as $term) {
foreach( get_ancestors( $term, $taxonomy ) as $term_id ) {
$ancestors[(int) $term_id] = (int) $term_id;
}
}
}
}
// When there is more than 1 parent product category
if( count($ancestors) > 1 ) {
wc_add_notice( __('Only products of the same category (Ambient, Chilled or Frozen) can be purchased together.'), 'error' );
$passed = false;
}
}
return $passed;
}
1条答案
按热度按时间2skhul331#
试试这个方法,把代码添加到你的functions.php文件中。