一次只允许购物车中的一个子类别

时间:2021-04-09 23:57:24

标签: php wordpress woocommerce

我将以下产品作为我的产品类别之一:

A 类

  • 孩子 1
  • 孩子 2
  • 孩子 3

每个孩子都有多种产品。我想让购物车中一次只能有一个子类别,但是,我希望能够添加该子类别中的所有产品。

我已尝试通过添加对类别 A 的子类别的查询来修改 Allow only one product category in cart at once in Woocommerce 答案,但它不起作用,并且阻止我将来自同一子类别的商品添加到购物车。

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) {


    // Child Query
    
    $term_id       = get_term_by( 'slug', 'category-A', 'product_cat' );
    $taxonomy_name = 'product_cat';
    $termchildren  = get_term_children( $term_id, $taxonomy_name );
    
    // if the product is in Category A
    if ( has_term( 'category-A', 'product_cat', $product_id )  ) {
        // Iterating through each cart item
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            
             if( ! has_term( $termchildren, $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;
}

0 个答案:

没有答案