1

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.

{# RANDOM IMAGE FROM SERVICES - 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>

            </div>
        </div>
    {% endfor %}
</div>
3

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 Jul 14 '16 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 :) – Mats Mikkel Rummelhoff Jul 14 '16 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 Jul 14 '16 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). – Mats Mikkel Rummelhoff Jul 15 '16 at 7:44

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.