根据子产品类别限制WooCommerce购物车



我希望使用WooCommerce的添加到购物车验证来限制特定类别的操作。

我有两个父类:A类和B类。

对于A类,它应该是不受限制的。因此,它可以随时添加到购物车中。

对于B类,我有不同的儿童类别。我希望限制它,以便在任何时候都只能在购物车中存在B类中的一个儿童类别。如果有人试图在购物车中已经有冲突的儿童猫时将第二个Cat B儿童类别产品添加到购物车中,我希望显示一条错误消息。

子类别将不断变化,因此按子猫ID进行查询不是一种选择——必须通过父类别进行查询。也可以选择将所有B类的子类别作为父类别,但我仍然需要将A类排除在限制之外。

基于在购物车回答代码中每个产品类别只允许一个产品,这就是我迄今为止所拥有的,我试图使其仅在添加的产品不是来自类别A:的情况下运行购物车循环

add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 );
function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) {
// Getting the product categories slugs in an array for the current product
$product_cats_object = get_the_terms( $product_id, 'product_cat' );
foreach($product_cats_object as $obj_prod_cat)
$product_cats[] = $obj_prod_cat->slug;
if ( ! $product_cats['cat-a-slug']) {

// Iterating through each cart item
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){
// When the product category of the current product does not match with a cart item
if( ! has_term( $product_cats, 'product_cat', $cart_item['product_id'] ))
{
// Don't add 
$passed = false;

// Displaying a message
wc_add_notice( 'Only one product from a category is allowed in cart', 'error' );
// We stop the loop
break;
}
}
}
return $passed;
}

这符合我对B类产品的要求,但也限制了我不想要的A类产品。

虽然也有类似的问题有可靠的答案,但我还没有找到一个能解决我问题的问题。我似乎无法忽视A类,所以它是不受限制的,或者正确阅读儿童类别。

如果您的代码符合类别B的逻辑,您可以添加此控件以始终允许将属于类别A的产品添加到购物车中:

// if the product belongs to category A allows the addition of the product to the cart
if ( has_term( 'cat-a-slug', 'product_cat', $product_id ) ) {
return $passed;
}

因此,完整的功能将是:

add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 );
function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) {
// if the product belongs to category A allows the addition of the product to the cart
if ( has_term( 'cat-a-slug', 'product_cat', $product_id ) ) {
return $passed;
}
// Getting the product categories slugs in an array for the current product
$product_cats_object = get_the_terms( $product_id, 'product_cat' );
foreach ( $product_cats_object as $obj_prod_cat ) {
$product_cats[] = $obj_prod_cat->slug;
}
// if the product belongs to category B
if ( in_array( 'cat-b-slug', $product_cats ) ) {
// Iterating through each cart item
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// When the product category of the current product does not match with a cart item
if ( ! has_term( $product_cats, 'product_cat', $cart_item['product_id'] ) ) {
// Don't add 
$passed = false;

// Displaying a message
wc_add_notice( 'Only one product from a category is allowed in cart', 'error' );
// We stop the loop
break;
}
}
}
return $passed;
}

我还没有测试代码,但它应该可以工作。将其添加到活动主题的函数.php中。

最新更新