Support

Account

Home Forums ACF PRO How to access subfields of post from relationship

Unread

How to access subfields of post from relationship

  • Hello

    I got a CPT A that contains a relationship field from another CPT B.

    <?php if ( have_rows( 'cpt_a_group' ) ) : ?>
        <?php while ( have_rows( 'cpt_a_group' ) ) : the_row(); ?>
    
            <?php $relate_a_b = get_sub_field( 'relate_a_b' ); ?>
    	<?php if ( $relate_a_b ) : ?>
    	    <?php foreach ( $relate_a_b as $post ) : ?>
    		<?php setup_postdata ( $post ); ?>
    		<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    	    <?php endforeach; ?>
    	<?php wp_reset_postdata(); ?>
    	<?php endif; ?>
    
        <?php endwhile; ?>
    <?php endif; ?>

    This is the code that bring back results.

    My question is, how can i get show fields that exist in a group within CPT B?

    If i try, for example:

    
    <?php if ( $relate_a_b ) : ?>
       <?php foreach ( $relate_a_b as $post ) : ?>
    
          <?php setup_postdata ( $post ); ?>
    	 <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
             <?php $logo = get_sub_field( 'logo' ); ?>
    	 <?php if ( $logo ) : ?>
    	    <img src="<?php echo esc_url( $logo['url'] ); ?>" alt="<?php echo esc_attr( $logo['alt'] ); ?>" />
    	 <?php endif; ?>
    
        <?php endforeach; ?>
        <?php wp_reset_postdata(); ?>
    <?php endif; ?>
    

    i dont get the logo back.

    I have managed to find a solution but there HAS to be an easier way to do this. This is what i have done (throws warnings and its generally ugly)

    
    <?php if ( $relate_a_b ) : ?>
       <?php foreach ( $relate_a_b as $post ) : ?>
    
          <?php setup_postdata ( $post ); ?>
    	 <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    
             <?php 
               $relate_b_a = get_field('relate_b_a ', $post->ID);
               $cpt_B_post_ID = $relate_b_a[0]->ID;
               $cpt_B_post_fieldgroup = get_field('cpt_B_post_fieldgroup', $cpt_B_post_ID);
               $the_logo = $cpt_B_post_fieldgroup ['logo']['url']; 
             ?>
    
           <?php if($the_logo) : ?>
             <img ... ... />
           <?php endif; ?>
    
        <?php endforeach; ?>
        <?php wp_reset_postdata(); ?>
    <?php endif; ?>
    

    Thanks!

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.