Link to relationship post

I am working on a WordPress website that has installed Advanced Custom Fields. One of the pages is showing a release by a band. I have created a custom post type for releases and one for lyrics. The release has a flexible content field called 'tracklist'. This field has a layout called 'tracks' with a row with two fields called 'trackname' (text), and 'lyrics' (relationship). 'lyrics' has been set to max one post, so you can only choose the lyrics for that specific song.

How am I able to get the link from this relationship field called 'lyrics'?

Read More

Here’s the code I have so far, but of course $lyrics contains an array, so it won’t work:

// check if the flexible content field has rows of data
if( have_rows('tracklist') ):

    $x = 1;
    echo '<p class="tracklist">';
     // loop through the rows of data
    while ( have_rows('tracklist') ) : the_row();

        if( get_row_layout() == 'tracks' ):
            $trackname = get_sub_field('trackname');
            $lyrics = get_sub_field('lyrics');

            echo '<strong>'.$x.'</strong> '.$trackname.' <a href="'.$lyrics.'">(lyrics)</a><br />';
        endif;
        $x++;

    endwhile;

    echo '</p>';


endif;

From the website of the plugin, I found this code. But is there an easier way as there only are one relationship?

<?php 

$posts = get_field('relationship_field_name');

if( $posts ): ?>
    <ul>
    <?php foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT) ?>
        <li>
            <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a>
            <span>Custom field from $post: <?php the_field('author', $p->ID); ?></span>
        </li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>

Related posts