Woocommerce:每次交易仅限客户一类

时间:2014-07-22 11:14:10

标签: php wordpress woocommerce

想知道是否有人可以提供帮助。

我想找到一个附加组件或者创建一些我自己的工作,只允许客户从每个交易的一个类别购买。

例如,他们可以从X类购买,但一旦他们选择了该类别的产品,他们将无法再从Y类购买。他们必须先完成交易。我显然需要一条错误信息来解释这一点。

是否有任何附加功能?你会怎么做?

这是我目前的思考计划,但我需要就这是否是最佳解决方案提出建议:

1. Loading product page

2. Check cart contents to see if products exist already

   a. product already exists in cart = check it's category

      i. same category? display "add to cart button"
      ii. not same category? display error message instead of button

   b. no product in cart? display "add to cart button"

1 个答案:

答案 0 :(得分:2)

function is_product_the_same_cat($valid, $product_id, $quantity) {
    global $woocommerce;
    // start of the loop that fetches the cart items
    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' ); //get the current items
        foreach ($terms as $term) {
            $cat_ids[] = $term->term_id;  //get all the item categories in the cart
        }
        foreach ($target_terms as $term) {
            $target_cat_ids[] = $term->term_id; //get all the categories of the product
        }           
    }
    $same_cat = array_intersect($cat_ids, $target_cat_ids); //check if they have the same category
    if(count($same_cat) > 0) return $valid;
    else {
        wc_add_notice( 'This product is in another category!', 'error' );
        return false;
    }
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);