0
votes

Running into issues adjusting the 'previous product' and 'next product' functionality within Shopify.

I'd like to set it up so that the 'previous' and 'next' loops through all products, carousel style.

Once you're at the last product,'next' will take you back to the first. At the moment, once you reach the end, you can only go to a previous product and backwards through the list.

Any thoughts?

Here's my base code:

  {% if collection.previous_product %}

     {{ '«' | link_to: collection.previous_product }}

  {% endif %}

  {% if collection.next_product %}

    {% if collection.previous_product %} | {% endif %}

    {{ '»' | link_to: collection.next_product }}

  {% endif %}
2

2 Answers

2
votes

Try something like this:

{% if collection.previous_product %}
  {{ '«' | link_to: collection.previous_product }}
{% else %}
  {% assign last_product_url = collection.products.last.url | within:collection %}
  {{ '«' | link_to: last_product_url }}
{% endif %}

{% if collection.next_product %}
  {{ '»' | link_to: collection.next_product }}
{% else %}
  {% assign first_product_url = collection.products.first.url | within:collection %}
  {{ '»' | link_to: first_product_url }}
{% endif %}

If you have more than 50 products in your collection, you should note that collection.products is paginated.

See here for info on the within filter.

0
votes

I'm not super familiar with Shopify, but I took a look at their docs and see the collections object includes colection.products_count and collection.products. If collection.products contains an array of the products, with their methods bound to them, you could do something like this:

{% if collection.previous_product %}

  {{ '«' | link_to: collection.previous_product }}

{% else %}

  {{ '«' | link_to: collection.products[collection.products_count - 1].url }}

{% endif %}

{% if collection.next_product %}

  {{ '»' | link_to: collection.next_product }}

{% else %}

  {{ '»' | link_to: collection.products[0].url }}

{% endif %}

I can't seem to find a shopify sandbox to test in, but assuming collection.products returns an array, this should work.