Skip to content

Instantly share code, notes, and snippets.

@plpepin
Last active August 30, 2018 01:15
Show Gist options
  • Save plpepin/59821732ac73eacec45829b3b1d1b96b to your computer and use it in GitHub Desktop.
Save plpepin/59821732ac73eacec45829b3b1d1b96b to your computer and use it in GitHub Desktop.
Shopify Random Category
{%- comment -%} Get the max amount of collections{%- endcomment -%}
{%- assign max_nb = collections.size -%}
{%- comment -%} Get a random seed based on seconds {%- endcomment -%}
{%- assign random_seed = "now" | date: "%S" %}
{%- if max_nb > 60 -%}
{%- comment -%} The max is MORE than 60 seconds. So we add the difference to the seed {%- endcomment -%}
{%- assign collection_size_difference = max_nb | minus: 60 -%}
{%- if random_seed > random_seed -%}
{%- comment -%}
This is to say..
IF we have a difference of 7, at 8 it will
add the difference, giving a chance for the
seed to reach the max amount of collections.
OTHERWISE, we give a chance for a collection
to be selected that is between 0 to 7
{%- endcomment -%}
{%- assign random_seed = random_seed | plus: collection_size_difference -%}
{%- endif -%}
{%- else -%}
{%- comment -%} The max is LESS than 60 seconds. So we remove the difference to the seed and make sure it doesn't go below 0 {%- endcomment -%}
{%- assign collection_size_difference = 60 | minus: max_nb -%}
{%- assign random_seed = "now" | date: "%S" | minus: collection_size_difference | at_least: 0 -%}
{%- endif -%}
@plpepin
Copy link
Author

plpepin commented Aug 30, 2018

An example of needing 3 random collections, I came up with the following:

{%- assign random_nb_1 = random_seed -%}
{%- assign random_nb_2 = random_nb_1 | minus: 7 | at_least: 0 -%}
{%- assign random_nb_3 = random_nb_1 | plus: 5 | at_most: max_nb -%}

@plpepin
Copy link
Author

plpepin commented Aug 30, 2018

Its far from perfect but its a start lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment