2

How can I limit the output of assets based on this criteria?

  1. search all entries randomly in section "homes" for only entries with at least one asset image
  2. limit those results to 8 random assets

I tried this but it does not always show exactly 8 asset images as the random is called first:

{% set assets = craft.assets.limit(null) %}

{% for homesEntry in craft.entries.section('homes').limit(8).order('RAND()') %}
    {% if homesEntry.homeImages|length %}
        {% set asset = homesEntry.homeImages.first() %}

        {% if asset %}
            <a href="{{ homesEntry.url }}"><img src="{{ asset.url('homeImages') }}" alt="{{ asset.title }}"></a>
        {% endif %}
    {% endif %}
{% endfor %}

Any help is appreciated.

3

This is how you do it in case anyone is looking for this.

{% set assets = craft.assets.limit(null) %}

{% set randomEntry = craft.entries.section('homes').order('RAND()').relatedTo({
    targetElement: assets,
    field: 'homeImages'
}) %}

{% for homesEntry in randomEntry.limit(6) %}
    {% set asset = homesEntry.homeImages.first() %}

    {% if asset %}
        <a href="{{ homesEntry.url }}"><img src="{{ asset.url('galleryImages') }}" alt="{{ asset.title }}"></a>
    {% endif %}
{% endfor %}
| improve this answer | |

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.