I have a field in a channel called "weight" where the user can set a number between 0-1000. On page load I want to generate a random number between 0 and "weight" for each entry, and then sort the entries based on these numbers.

How can I do this with Craft 2/Twig?


Would be a lot cleaner/more efficient to do this from a custom plugin in PHP, but if you want to do it from a template, this should work:

{% set entryArr = {} %}

{# Grab all of the entries in the section #}
{% set entries = craft.entries.section('news').find() %}

{# Loop through them generating a random number between 0 and the weight custom field #}
{% for entry in entries %}
    {% set entryArr = entryArr|merge({(entry.slug): random(range(0, entry.weight))}) %}
{% endfor %}

{# Sort the array by the ascending value maintaining the keys #}
{% set entryArr = entryArr|sort %}

{# print them off #}
{% for slug, randomNumber in entryArr %}
    {% set entry = craft.entries.slug(slug).first() %}
    <li>{{ entry.title }} - Max Range: {{ entry.randomNumber }} - Random Number: {{ randomNumber }}
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.