I am trying to pull an image from services marked with a category of left. I would only like to display one image. I would also like to randomize the image if possible from all the images marked left.

<div class="grid-item">
    {% for homepage in craft.entries.section('services').limit('1').relatedTo(left).find() %}
        <div class="image-wrapper overlay-fade-in">

            <img src="{{ homepage.homepageImage.first().getUrl }}" alt="{{ homepage.title }}"/>

            <div class="image-overlay-content">

                <h2>{{ homepage.title }}</h2>
                <p>{{ homepage.description }}</p>
                <a href="services.html" class="button">View Rental Pricing</a>

    {% endfor %}

1 Answer 1


Welcome to the Craft community @bjyama

{# Step one: pick a random service #}
{% set randomService = craft.entries.section('services').relatedTo(left).order('RAND()').first() %}

{# Step two: pick a random image from the above service #}
{% set randomServiceImage = service.homepageImage.order('RAND()').first() %}

{% if randomServiceImage %}
    <img src="{{ randomServiceImage.getUrl('imageTransformName') }}" alt="">
{% endif %}

For more info, have a look here: https://craftcms.com/docs/templating/craft.entries#order

Let us know how you get on :)

  • Fair enough, cheers Mats!
    – Matt P
    Commented Jul 14, 2016 at 10:19
  • 1
    Yeah, the for loops weren't neccessary/would fail as you're using first() :) Could do with a conditional testing the randomService variable, but otherwise this looks legit – assuming left is a CategoryModel instance, of course :) Commented Jul 14, 2016 at 10:25
  • I'm beginning to understand the code above. However, when you say "assuming left is a CategoryModel instance" what do you mean? I have created a Category called homepageView and then created two categories in it called right and left. I then created a category field called homepageImageLayout and added it to my services channel. I selected left in one of the entries.
    – bjyama
    Commented Jul 14, 2016 at 21:17
  • @bjyama .relatedTo(left) will only work if the variable left is actually set to a category (i.e. an instance of CategoryModel). By itself, using left will only throw an error (undefined variable). From your description, I'm don't really understand how you structured this so I'm unable to give you a good example, but you'll need something like {% set left = craft.categories.group('yourCategoryGroupHandle').slug('left').first() %} somewhere in your template (before the {% set randomService... part). Commented Jul 15, 2016 at 7:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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