Skip to content
Advertisement

output the_field of related posts with ACF Relationship

and first off all, thanks for help.

I have to following code to display related posts from one custom post type to another with ACF Relationships.

what i want to know, is it possible and how can i rewrite the code, to output any custom field of the related post that i have selected with the relationship field?

<?php 
$posts = get_field('product_id');

    if( $posts ): ?>
        <ul>
        <?php foreach( $posts as $p ): ?>
            <li>
                <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a>
            </li>
        <?php endforeach; ?>
        </ul>
  <?php endif; ?>

like i do here, is:

echo get_permalink( $p->ID );

i want to echo:

the_field('field_name')

regards, Axel

Advertisement

Answer

If you check the documentation of the the_field() function you’ll notice that it can take the post/page ID as the second parameter so you can retrieve the field value of a specific post/page field:

Parameters

the_field($selector, [$post_id], [$format_value]);

  • $selector (string) (Required) The field name or field key.
  • $post_id (mixed) (Optional) The post ID where the value is saved. Defaults to the current post.
  • $format_value (bool) (Optional) Whether to apply formatting logic. Defaults to true.

So, for example:

<?php
$posts = get_field('product_id');

if( $posts ): ?>
    <ul>
    <?php foreach( $posts as $p ): ?>
        <li>
            <a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a>

            <?php the_field('field_name', $p->ID); ?>
        </li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement