Search code examples
phpwordpresstwigadvanced-custom-fieldstimber

Wordpress - I can't display the title of a relationship field's selected item in Twig/Timber


I a new to Twig/Timber. I have a single post that has an ACF relationship field that allows you to choose from a particular post type (call it "training"). Say I have a post in training called "Aerobics", and that's the one I choose in the relationship field. On the page, I want to display the title and date of Aerobics.

In Timber, I have defined that as

$context['related_training'] = get_field('related_pd_interactive_training');

what I don't know is how to display it. Both of these return true, but when I try to display the title of the item in the Relationship Field, it get nothing

{% for trainings in post.meta('related_pd_interactive_training') %}
   {{ WHAT DO I DO HERE }}
{% endfor %}

or

{% if post.related_pd_interactive_training %}
   {{ OR HERE }}
{% endif %}

Solution

  • When you use get_field() directly, it will work for singular templates, but it wouldn’t work in archive templates, because you don’t pass the post ID.

    $context['related_training'] = get_field( 'related_pd_interactive_training' );
    

    To make it work the Timber way, you would do it the following way:

    $context = Timber::get_context();
    
    $context['post'] = Timber::get_post();
    

    You can then make use of a post’s meta() function:

    {% for training in post.meta('related_pd_interactive_training') %}
        {{ dump(training) }}
    {% endfor %}
    

    Now, training is probably only a post ID, depending on what you defined as a return value in your ACF field. To turn training into a Timber post where you can access the title and the date, you have multiple options:

    1. Prepare it in PHP

    To prepare your data in PHP, you could use array_map to loop over the post IDs saved in related_pd_interactive_training and turn them into Timber posts by calling new Timber\Post().

    $context = Timber::get_context();
    $post    = Timber::get_post();
    
    $context['trainings'] = array_map( function( $training ) {
        return new Timber\Post( $training );
    }, $post->meta( 'related_pd_interactive_training' ) );
    

    To go one step further here, you could put that function into a new method by Extending Timber.

    2. Use Post() in Twig

    A shorter way to do this would be to use Post() in Twig, which turns a post ID or an array of of post IDs that you pass to Timber posts.

    {% for training in Post(post.meta('related_pd_interactive_training')) %}
        {{ training.title }}
        {{ training.date }}
    {% endfor %}