Use Timber/Twig to pull an image by image ID [closed]

Is it possible to use Twig to pull an image by ID, or only to pull the post.thumbnail? The Twig docs don’t seem to cover any other image need and I’d like to specify a backup image in case no post.thumbnail is found.

I think what I need is something like wp_get_attachment_image_src(1234,'medium_16x9') but in Twig’s language.

    <a href="https://wordpress.stackexchange.com/questions/228726/{{post.link}}">
        {% if post.thumbnail %}
        <img src="https://wordpress.stackexchange.com/questions/228726/{{ post.thumbnail.src("medium_16x9') }}">
        {% else %}
        <img src="{{ wp_get_attachment_image_src(1234,'medium_16x9') }}">
        {% endif %}
    </a>

I suppose I could set this up in the PHP by adding the backup image URL to a variable, but this means I’d have to add that code to every PHP file that calls this twig. It’s better to grab the image in the twig, no?

1 Answer
1

{{ post.thumbnail.ID }} will get you the image ID, but to answer what you’re after….

<img src="https://wordpress.stackexchange.com/questions/228726/{{ post.thumbnail.src("medium_16x9') | default( Image(1234).src('medium_16x9') ) }}">

Reference

Leave a Comment