Shopify Product Page Dropdown by Tags part 2


I previously wrote a blog about my exploration of a task required of a Shopify merchant here. The only shortcoming I had to overcome was the “hard coded” value of the grouping in the liquid file. I found a way to overcome this issue, see the code here:

{% assign all_products = collections.all.products %}
{% assign curProductTag = "" %} <!-- Initialize value to check if the current product has an associated group -->

{% for tag in product.tags %}
  {% if tag contains "drop-down-list-" %} <!-- Check if the tag contains the keyword "drop-down-list-" which indicates grouping -->
    {% assign curProductTag = tag | remove: 'drop-down-list-' %} <!-- Strip out the identifier to get the current product tag -->
  {% endif %}
{% endfor %}

{% if curProductTag != blank %} <!-- If the current product has an associated group -->
  <div class="dropdown">
    <button class="btn dropdown-toggle" type="button" id="collectionDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      {{ product.title }} <span class="arrow-down">&#9660;</span> <!-- Display the product title and the downward arrow -->
    </button>
    <div class="dropdown-menu" aria-labelledby="collectionDropdown">
      {% for prod in all_products %}
        {% assign showProduct = 'false' %}
        {% assign temp = "" %}
        {% for tag in prod.tags %}
          {% if tag contains "drop-down-list-" %}
            {% assign showProduct = 'true' %}
            {% assign temp = tag | remove: 'drop-down-list-' %}
          {% endif %}
        {% endfor %}
        {% if showProduct == 'true' and curProductTag == temp and product.title != prod.title %}
          <a class="dropdown-item" href="{{ prod.url }}">{{ prod.title }}</a> <!-- Display the associated products within the dropdown menu -->
        {% endif %}
      {% endfor %}
    </div>
  </div>
{% endif %}

The key here is checking for the drop-down-list- in the product tags. If you were grouping together a set of Amber candles for example, the merchant could simply add drop-down-list-amber-candles to the product tags of any products in the set, and they would appear in the dropdown button.

This approach does have some shortcomings that should be addressed. For example, this requires EVERY SINGLE product to be looped through, with a nested loop going through the tags of each product. Not good for performance! I mistakenly thought that only one collection could be assigned to a product, which is not the case. Perhaps this same approach could be used with collections instead of tags? That could certainly improve performance factors. Stay tuned…