[英]Only allow add to cart from products of the same parent category in WooCommerce
I am working with two main parent categories on my store, each one subdivided on almost 10 categories. 我在商店中使用两个主要的父类别,每个类别又细分为近10个类别。
I have a script that limits to 1 the number of categories added to the cart, What can I do to change it to only parent categories?, so I can select multiple products of the same kind. 我有一个脚本,将添加到购物车中的类别数量限制为1个,我该怎么做才能将其更改为仅父类别?因此我可以选择多个相同种类的产品。
function is_product_the_same_cat($valid, $product_id, $quantity) {
global $woocommerce;
if($woocommerce->cart->cart_contents_count == 0){
return true;
}
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
$target_terms = get_the_terms( $product_id, 'product_cat' );
foreach ($terms as $term) {
$cat_ids[] = $term->term_id;
}
foreach ($target_terms as $term) {
$target_cat_ids[] = $term->term_id;
}
}
$same_cat = array_intersect($cat_ids, $target_cat_ids);
if(count($same_cat) > 0) return $valid;
else {
wc_add_notice( 'Solo pueden comprarse productos de una misma categorÃa.', 'error' );
return false;
}
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);
Since WooCommerce 3, the code you are using is outdated… The following will work with the parent product category, allowing only add to cart from the same parent product category: 从WooCommerce 3开始,您使用的代码已过时……以下内容适用于父产品类别,仅允许从同一父产品类别添加到购物车:
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 can be purchased together.'), 'error' );
$passed = false;
}
}
return $passed;
}
Code goes in functions.php file of your active child theme (or active theme). 代码进入您的活动子主题(或活动主题)的functions.php文件中。 Tested and works.
经过测试和工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.