Hi All,
I tried the below code to control of the total number of product added to the cart depends on the shipping profile, tried to add to the main-cart-item.liquid but didn’t get any luck, does anyone have another solution to control the number of item added to the card? thanks a lot for your help.
{% assign shipping_profile_limits = {
“Small package”: 10,
“Middle Package”: 10,
“Large Package”: 10,
“Paper package”: 100
} %}
{% assign cart_item_counts = {} %}
{% for item in cart.items %}
{% assign shipping_profile = item.product.shipping_profile %}
{% if cart_item_counts[shipping_profile] %}
{% assign cart_item_counts[shipping_profile] = cart_item_counts[shipping_profile] | plus: 1 %}
{% else %}
{% assign cart_item_counts[shipping_profile] = 1 %}
{% endif %}
{% endfor %}
{% assign small_middle_large_count = 0 %}
{% assign paper_package_count = 0 %}
{% for shipping_profile, count in cart_item_counts %}
{% if shipping_profile in [“Small package”, “Middle Package”, “Large Package”] %}
{% assign small_middle_large_count = small_middle_large_count | plus: count %}
{% elsif shipping_profile == “Paper package” %}
{% assign paper_package_count = count %}
{% endif %}
{% endfor %}
{% if small_middle_large_count > 10 or paper_package_count > 100 %}
You have reached the maximum number of products allowed in your cart.
{% if small_middle_large_count > 10 %}
You can only add up to 10 products from Small, Middle, and Large packages combined.
{% endif %}
{% if paper_package_count > 100 %}
You can only add up to 100 products from Paper packages.
{% endif %}
{% endif %}
Jackie
The code you provided should generally work
refined version of the code to control the total number of products added to the cart based on shipping profiles:
{% assign shipping_profile_limits = {
"Small package": 10,
"Middle Package": 10,
"Large Package": 10,
"Paper package": 100
} %}
{% assign cart_item_counts = {} %}
{% for item in cart.items %}
{% assign shipping_profile = item.product.shipping_profile %}
{% if cart_item_counts[shipping_profile] %}
{% assign cart_item_counts[shipping_profile] = cart_item_counts[shipping_profile] | plus: item.quantity %}
{% else %}
{% assign cart_item_counts[shipping_profile] = item.quantity %}
{% endif %}
{% endfor %}
{% assign error_message = "" %}
{% for shipping_profile, limit in shipping_profile_limits %}
{% if cart_item_counts[shipping_profile] and cart_item_counts[shipping_profile] > limit %}
{% assign error_message = "You have exceeded the limit for " | append: shipping_profile | append: " (max: " | append: limit | append: " items)." %}
{% endif %}
{% endfor %}
{% if error_message != "" %}
{{ error_message }}
{% endif %}
Place this code in the relevant section where you handle the cart updates or display messages to users