Search code examples
wordpresstwigadvanced-custom-fieldstimber

Get ACF custom field in media - Twig/Timber


I created a gallery with ACF custom field "gallery". But I would like to add more settings on each photo.

For that I created two ACF custom fields that I added to the Wordpress Medias to determinate a size and a position for each image. On the screenshot below : "Taille" and "Position" dropdown lists are my custom fields.

In the back office : "photo_size" is the name of the custom field for the dropdown list "Taille" "photo_position" is the name of the custom field for the dropdown list "Position"

I manage to create my photo gallery but I don't manage to get those additional custom fields.

I tried this :

$file = get_field('show_gallery');
$photo_size = get_field('photo_size', $file['ID']);
$context['photo_gallery'] = $photo_size;

I try to get the value of 'photo_size' attached to each image :

{% for item in photo_gallery %}
    <img src="{{ Image(item).src }}" class="gallery__img {{ item.photo_size }}" alt="{{ Image(item).alt }}">
{% endfor %}

enter image description here


Solution

  • Is $photo_size an array? It doesn't look like it. What do you get if you {{ dump(photo_gallery) }}? Or var_dump($photo_size) in your php file? It looks like you should be looping through the show_gallery field not the photo_size field but it is difficult to tell given the field names and that we can't see your field setup (some language barrier here no doubt - if I could speak French I could probably get the idea better). Basically, we need to know how that show_gallery field is set up then I'm sure it will become clearer.

    So perhaps you should have something like:

    
    $context['photos'] = get_field('show_gallery');
    
    

    then

    {% for item in photos %}
        {% set photo_size = function('get_field','photo_size',item.id) %}
        <img src="{{ item.url }}" class="gallery__img {{ photo_size }}" alt="{{ item.alt }}">
    {% endfor %}>