1

I have a repeater field for Post Objects from which I want to obtain the title, excerpt and featured img values. So, these are NOT sub_fields, just common fields.

If I use the example code:

<?php
$post_objects = get_field('articulos_repeater');
if( $post_objects ): ?>
    <ul>
    <?php foreach( $post_objects as $post_object): ?>
        <li>
            <a href="<?php echo get_permalink($post_object->ID); ?>"><?php echo get_the_title($post_object->ID); ?></a>
            <span>Post Object Custom Field: <?php the_field('field_name', $post_object->ID); ?></span>
        </li>
    <?php endforeach; ?>
    </ul>
<?php endif;

?>

I get the values of the current page. But if I

print_r($post_object) 

I get the (in this case) four individual array objects I need.

Why is this happening?

  • I think something is wrong with your foreach loop. Can you post the contents of $post_objects right after you do the get_field? – gdaniel Aug 16 '17 at 17:08
  • Hi, @gdaniel The result is an array with nested array objects, one for each of the related posts. – MauF Aug 16 '17 at 17:15
  • I asked because if you look at the functions you are using, their default 'ID' parameter is the global post, so it's as if the $post_object->ID is empty and it's defaulting to the global post. – gdaniel Aug 16 '17 at 18:04
0

Try this alternative way of getting the post objects. Seeing as your loop seems to be using the global post data anyway, this method uses setup_postdata to set the global values.

$post_objects = get_field('post_objects');

if( $post_objects ): ?>
    <ul>
    <?php foreach( $post_objects as $post): // variable must be called $post (IMPORTANT) ?>
        <?php setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            <span>Post Object Custom Field: <?php the_field('field_name'); ?></span>
        </li>
    <?php endforeach; ?>
    </ul>
    <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif;

Reference: ACF Post Object documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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