Search code examples
phpwordpressadvanced-custom-fields

Cannot retrieve ACF values from Custom Post Type


I have a Custom Post Type called 'fotos' with a couple ACF fields connected to it.

Inside the while loop in my homepage i'm retrieving the most recent posts from this CPT. I want to show an ACF field called 'clients' for each of these posts. the $photo->ID is correctly returning the ID of the CPT post.

<?php
if (have_posts()) :
    while (have_posts()) : the_post(); ?>
<!-- ... -->
  <?php
    $recent_photos = wp_get_recent_posts(array(
        'numberposts' => '8',
        'post_type' => 'fotos',
        'post_status' => 'publish',
    ));
    if ($recent_photos):
        ?>

            <?php foreach ($recent_photos as $photo): ?>
                <div class="item-grid--item">
                    <?php the_field('client', $photo->ID); ?>
                </div>
            <?php endforeach; ?>

<?php endif; ?>
<!-- ... -->
    <?php endwhile;
else:
    _e('Sorry, no posts matched your criteria.', 'textdomain');
endif;
?>

However, the_field, get_field, the_sub_field or get_sub_field return absolutely nothing. What could it possibly be? I checked everything and it's all correct!


Solution

  • Default return value type of wp_get_recent_posts is an associative array not object.

    So you can change the return type of wp_get_recent_posts

    $recent_photos = wp_get_recent_posts(array(
            'numberposts' => '8',
            'post_type' => 'fotos',
            'post_status' => 'publish',
        ), object);
    

    or you can change the getting the ID in your default code.

    <?php the_field('client', $photo['ID']); ?>