Support

Account

Home Forums General Issues Displaying a relationship field only if it exists

Helping

Displaying a relationship field only if it exists

  • I’m having some trouble making this work…
    I’m trying to 1) pull in a relationship field from a connected post, but 2) only displaying that if it exists.

    First, I know how to display values from the same post’s ACF fields only if it exists:

    <?php if( $doesitexist = get_field('field_name') ){ ?>
    	<?php echo get_field_object('field_name')['label']; ?><br />
    	<?php the_field('field_name'); ?>
    <?php } ?>

    Got that. Second, I know how to connect the current post to another post-type’s post and display a field value from that other post…

    <?php $posts = get_field('doctors'); if( $posts ): ?>
    <?php foreach( $posts as $post): ?>
    <?php setup_postdata($post); ?>
    	<?php the_field('doctor_name'); ?>
    <?php endforeach; ?>
    <?php wp_reset_postdata(); ?>
    <?php endif; ?>

    My question is…how can I combine those so that the field label and name FROM a relationship-connected post will only show IF it exists?

  • I know this is an old question and the OP may not still be looking for help, but someone may have the same question.

    Using the above code to work from:

    
    global $post;
    $posts = get_field('doctors');
    if ($posts) {
        foreach ($posts as $post) {
            setup_postdata($post);
            $name = get_field('doctor_name');
            if ($name) {
                $field_object = get_field_object('doctor_name');
                echo $field_object[label],': ',$name;
            }
        } // end foreach
        wp_reset_postdata();
    } // end if posts
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Displaying a relationship field only if it exists’ is closed to new replies.