Code Example: A Shopify “Related Products” Selector

<!– Mark Foote, “product-collection-selector.liquid” snippet–>
<!– requires linklist with handle “all-collections” –>
<!– link titles in “all-collections” linklist must match collection titles –>
<!– collection with collection title must include all products for selector drop-down –>
<!– See Caroline Schnapp’s “related products” snippet: https://docs.shopify.com/support/your-store/products/can-i-recommend-related-products#finding-a-relevant-collecitons –>
{% comment %}
needs addition of {% include ‘product-collection-selector’ %} in product-form.liquid
{% endcomment %}

{% assign no_match = true %}

{% comment %}
Maximum number of products to display in selector
{% endcomment %}

{% assign counter = 0 %}

{% comment %}
Heading, if needed (or leave blank).
{% endcomment %}

{% assign heading = ‘Collection Products:’ %}

{% if product.collections %}
{% if linklists.all-collections %}
{% for c in product.collections %}
<span style=”display:none;”>c.title is: {{ c.title }}</span>
{% if no_match %}
{% for d in linklists.all-collections.links %}
{% if c.title == d.title %}
{% assign found_collection = c %}
{% assign no_match = false %}
{% break %}
{% endif %}
{% endfor %}
{% else %}
{% break %}
{% endif %}
{% endfor %}
{% else %}
<span name=”no_linklists_all-collections” style=”display:none;”>A collection with handle “all-collections” is required for the collection product selector (and an include for snippet “collection-product-selector” must appear in product-form.liquid) </span>
{% endif %}
{% else %}
<span name=”no_linklists_all-collections_2″ style=”display:none;”>A collection with handle “all-collections” is required for the collection product selector (and an include for snippet “collection-product-selector” must appear in product-form.liquid) </span>
{% endif %}

{% assign current_product_url = product.url %}

{% capture collection_items %}
<option value=”{{ product.url }}”>{{ product.title }}</option>
{% for product in found_collection.products %}
{% unless product.handle == current_product.handle %}
{% assign product_url = product.url %}
{% unless current_product_url == product_url %}
<option value=”{{ product.url }}”>{{ product.title }}</option>
{% assign counter = counter | plus: 1 %}
{% endunless %}
{% endunless %}
{% endfor %}
{% endcapture %}

{% assign collection_items = collection_items | trim %}

{% unless collection_items == blank %}
{% unless counter < 1 %}
<aside>
<label for=”collection-products”>{{ heading }}</label>
<select id=”collection-products” name=”collection-products”>
{{ collection_items }}
</select>
</aside>
{% endunless %}
{% endunless %}

<script>
$( document ).ready(function() {
$(‘#collection-products’).change(function(){
var product_path = $(this).val();
$(location).attr(‘href’,product_path);
});
});
</script>