Skip to main content

Choosing which post attachment gets displayed

I apologize in advance if this question is a bit convoluted..

The site womensvoicesnow.org is a repository of films. Each individual film page is a blog post. The main blog page that shows the catalogue of films http://womensvoicesnow.org/films is designed like film cards, each with a thumbnail image. That image is grabbed using the following code: {{ post.attachments.first.url }}. I think I'm not understanding what the "first" means in this. It doesn't seem to mean the first image to be uploaded in the files for that page, nor does it mean the first one in the list of files uploaded, nor does it seem to mean the first image that appears in the post. It seems like every film behaves differently.  Some films have only one post attachment, but others have several. Is there a way I can specify which image gets placed in the film card?

Thanks in advance!

 

Official response from

Hi Alison - 

I have noticed this myself in a few instances. For example, on a different site/theme/page I found that the attachments were sorted alphabetically by the attachment file type, meaning that PDF files, which had the attachment type name "application" came before images, which had the type name "image/jpeg" -- definitely confusing.

In any case, there is a really good way to code the page template that makes it super easy for someone to determine which attachment gets used without them having to edit the code each time.

 

Your code probably looks somewhat like this by default:

<img src="{{ post.attachments.first.url }}">

But you could use a liquid forloop to scan through all of the attachments and just take the one with a particular term in the file name, like so:

{% for attachments in post.attachments %}

{% if attachment.file_name contains "thumbnail" %}

<img src="{{ attachment.url }}">

{% endif %}

{% endfor %}

When this is implemented, it will use whatever image has "thumbnail" in the file name. Please note that you should then make sure to only have one attachment with "thumbnail" in the file name for each post.

Share this post

Showing 2 reactions

How would you tag this suggestion?
Please check your e-mail for a link to activate your account.