Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Hello I am using advanced custom fields and I am trying to pull data from multiple pages and display it on another

I set up a relationship field called "data", and then on page X where the relationship field is displayed I have chosen page Y where I want to pull the data from

<?php if( get_field('data') ): ?>
     <?php the_field('special_offer'); ?> <!--// get content from page Y -->
<?php endif; ?>

I can't get this to work though and Im presuming the above is wrong, does anyone know how I could do this please?

Hopefully I have explained it clearly

Cheers

<?php if( $related_pages = get_field( 'special_offer_relationship' ) ): ?>

    <?php foreach( $related_pages as $page ): ?>
        <?php echo get_the_title( $page->ID ); ?>
        <?php echo get_the_excerpt( $page->ID ); ?>
   <?php endforeach; ?>

<?php endif; ?>
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

The relationship field returns an array of post objects. Each post object contains the ID of the related post. The ACF field functions accept a second parameter, which is the post ID you want to retrieve data from, if it is not the current post.

if( $related_pages = get_field( 'data' ) ):
    foreach( $related_pages as $page ):
        the_field( 'special_offer', $page->ID );
    endforeach;
endif;

All of this is from the ACF documentation, which is pretty thorough with many examples.

EDIT

If you want to use template tags that require the global $post var, you have to use setup_postdata() to populate it with the post's data. Note that get_the_excerpt does not accept a post ID like get_the_title does.

if( $related_pages = get_field( 'data' ) ):
    foreach( $related_pages as $post ): // you must use $post for this to work
        setup_postdata( $post );
        the_title();
        the_excerpt();
    endforeach;
    wp_reset_postdata(); // restore global $post for outer loop
endif;
share|improve this answer
    
Sorry on the late reply and thanks a lot for the reply! For some reason get_the_excerpt, or content is just getting the content from the page you are on, I dont suppose you know of what might be causing this or if I am doing something wrong? (I have updated the op) Strangely enough it gets the title fine but not the content :S –  adam Sep 15 '13 at 15:56
    
see edit above. –  Milo Sep 15 '13 at 16:08
    
Awesome thanks! –  adam Sep 15 '13 at 16:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.