Ad

Allow Shopify Cart To Checkout Only If All Cart Items Have Same Specific Tag

- 1 answer

Here’s my situation:

  • I have products set up with 2 major collections/tags: day(example: monday-product) and location (example: location-vegas). All day tags have the same "-product" suffix and each location tag has the same "location-" prefix
  • All products can be tagged with one day tag "monday-product" and one location tag “location-vegas”.
  • If a person buys a product with the tags “location-vegas” and another product with the tag “location-la”, the checkout doesn’t work because it doesn’t have matching "location-“ tags between them.

I can't seem to figure out the coding for the checkout to look if all products have matching "location-" tags. I would also like to do the same with the "-product" tags.

I've tried this code but it only looks if either is there, not if each has at least one matching:

{% for item in cart.items %}
    {% assign different_locations = false %}
    {% if item.product.tags == 'location-atwater' or 'location-nordelec' or 'location-place-ville-marie' %}
    {% assign different_locations = true %}
    {% endif %}
    {% endfor %}

    {% if different_locations == true %}
    [ 'CANNOT COMPLETE ORDER' ]
    {% else %}
    <p>
      <input type="submit" class="action_button add_to_cart" id="checkout" name="checkout" value="{{ 'cart.general.checkout' | t }}" />
    </p>
    {% endif %}

Hoping the stack overflow community can help.

Ad

Answer

Find all location tags and then filter by unique tags:

{% assign location_tags = '' %}

{% for item in cart.items %}
  {% for tag in item.product.tags %}
      {% if tag contains 'location' %}
        {% capture location_tags %}{{ location_tags }},{{ tag }}{% endcapture %}
      {% endif %}
  {% endfor %}
{% endfor %}

{% assign unique_location_tags = location_tags | remove_first: ',' | split: ',' | uniq %}

{% if unique_location_tags.size > 1 %}
  Disable checkout button...
{% endif %}

Alternatively, you could choose to only add unique location tags to the array to begin with (and then you don't need the uniq filter):

{% if tag contains 'location' %}
  {% unless location_tags contains tag %}
    {% capture location_tags %}{{ location_tags }},{{ tag }}{% endcapture %}
  {% endunless %}
{% endif %}
Ad
source: stackoverflow.com
Ad