Filtering a collection by tag using a drop-down

From Shopify Wiki

Jump to: navigation, search

Image:Jitensha Playground — Shopify.png

To add to your collection page a drop-down that lists all tags within your collection, add the following code to your collection.liquid template.

That snippet will work on regular collection pages — those collections you created under the Collection tab — as well as on automatic collection pages.

<div class="clearfix filter">
  <p>Browse by tag:</p>
  <select class="coll-filter">
    <option value="">All</option>
    {% for tag in collection.all_tags %}
    {% if current_tags contains tag %}
    <option value="{{ tag | handle }}" selected>{{ tag }}</option>
    {% else %}
    <option value="{{ tag | handle }}">{{ tag }}</option>
    {% endif %}
    {% endfor %}
  </select>
</div>

<script>
  /* Product Tag Filters - Good for any number of filters on any type of collection pages */
  /* Brought to you by Caroline Schnapp */
  var collFilters = jQuery('.coll-filter');
  collFilters.change(function() {
    var newTags = [];
    collFilters.each(function() { 
      if (jQuery(this).val()) {
        newTags.push(jQuery(this).val());
      }
    });
    if (newTags.length) {
      var query = newTags.join('+');
      window.location.href = jQuery('{{ 'tag' | link_to_tag: 'tag' }}').attr('href').replace('tag', query);
    } 
    else {
      {% if collection.handle %}
      window.location.href = '/collections/{{ collection.handle }}';
      {% elsif collection.products.first.type == collection.title %}
      window.location.href = '{{ collection.title | url_for_type }}';
      {% elsif collection.products.first.vendor == collection.title %}
      window.location.href = '{{ collection.title | url_for_vendor }}';
      {% endif %}
    }
  });
</script>

Related Articles