WooCommerce 购物车分类限制

WooCommerce Cart Taxonomy Limit

我为 WooCommerce 产品创建了一个自定义分类法(slug:餐厅),我目前正在使用它来过滤产品。我需要限制一次可以添加到购物车的餐厅数量。以下代码限制了“产品”的数量而不是“分类”。感谢任何帮助。

public function CheckRestaurantInCart($product_id){
            if( WC()->cart->is_empty() )
                return true;

            foreach ( WC()->cart->get_cart() as $cart_item ) {
                $ci[] = $cart_item['data']->get_category_ids();
            }

            $terms = get_the_terms ( $product_id, 'restaurant' );

            $cat_output = array_unique($ci, SORT_REGULAR);
            $cat_count = count($cat_output);
            $allowed_count = 2;

            //check whether the cart has the same restaurant and ignore
            if (in_array_r($terms[0]->term_id, $cat_output))
                return true;

            if ($cat_count >= $allowed_count) {
                wc_add_notice( __('Restaurant count allowed is: '. $allowed_count .' at this time'), 'error' );
                return false;
            }
            return true;

        }

Taxonomy view

您可以使用 has_term 检查给定类别的产品是否已经在购物车中。试试下面的代码。

public function CheckRestaurantInCart($product_id){

    if( WC()->cart->is_empty() )
        return true;

    $allowed_count = 2;

    if ( $this->restrict_product_from_same_category( $product_id, $allowed_count ) ) {
        wc_add_notice( __('Restaurant count allowed is: '. $allowed_count .' at this time'), 'error' );
        return false;
    }
    return true;

}

public function restrict_product_from_same_category( $product_id, $allowed_count ) {

    $passed = false;

    if( ! WC()->cart->is_empty() ) {
        // Get the product category terms for the current product
        $terms_slugs = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'slugs' ) );
        $cat_count = 0;
        foreach ( WC()->cart->get_cart() as $cart_item ){
            if( has_term( $terms_slugs, 'product_cat', $cart_item['product_id'] ) ) {
                $cat_count = $cat_count + $cart_item['quantity'];
            }
        }

        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ){
            if( has_term( $terms_slugs, 'product_cat', $cart_item['product_id'] ) ) {
                if( $cat_count >= $allowed_count ){
                    $passed = true;
                    break;
                }
            }
            $cat_count++;
        }

    }
    
    return $passed;
}

已测试并有效