PHP woocommerce Limit cart quantity for a product based on category

If you want to set maximum quantities for a products you can use this code in your WordPress/woocommerce plugin.

add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_items_from_category', 10, 3 );
function limit_cart_items_from_category ( $passed, $product_id, $quantity )
{
    // Accept when cart is empty
    if( WC()->cart->is_empty() ) return $passed;

    // HERE your product categories in this array (can be names, slugs or Ids)
    $categories = array('Biletler');
    $found = $current = false;

    // Check the current product
    if( has_term( $categories, 'product_cat', $product_id ) ){
        $current = true;
    }

    // Loop through cart items checking for product categories
    foreach ( WC()->cart->get_cart() as $cart_item ){
        if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $found = true;
            break; // stop the loop.
        }
    }

    // Current product and a cart item match with defined product categories
    if( $found && $current ){
        $passed = false;
        $cats_str = implode('" and "', $categories );
        wc_add_notice( sprintf( __('Aynı anda sadece 1 etkinlik için bilet satınalabilirsiniz.', 'woocommerce' ), $cats_str ), 'error' );
    }
    return $passed;
}

To improve this article ansver those questions :

Set minimum and maximum quantities in WooCommerce

Only Allow 1 Product in the Cart

Leave a Reply

Your email address will not be published. Required fields are marked *