Tasha Banks
Tasha Banks

Reputation: 38

WooCommerce Cart Taxonomy Limit

I have created a custom taxonomy (slug: restaurant) for WooCommerce products where I am currently using to filter products. I need to limit the number of Restaurants that can be added to the cart at once. The following code limits the number of "products" rather than the "taxonomy". Any help is appreciated.

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

Upvotes: 0

Views: 76

Answers (1)

Bhautik
Bhautik

Reputation: 11282

You can use has_term to check product of a given category already is in the cart or not. Try the below code.

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;
}

Tested and works

enter image description here

Upvotes: 1

Related Questions