1

I have a custom image field for all pages with a specific page template (using ACF plugin).

I'm querying for these pages like so:

    $posts = get_posts(array(
    'posts_per_page'    => -1,
    'post_type'         => 'page',
    'meta_key'      => '_wp_page_template',
    'meta_value'    => 'services-page.php'
));

Then I'm displaying pages with a foreach loop:

if( $posts ): ?>
<?php foreach( $posts as $post ): setup_postdata( $post );?>
//content goes here
<?php endforeach; ?> 
<?php wp_reset_postdata(); ?>
<?php endif; ?>

Now I want to access the custom field to display inside the loop. But, below doesn't work. I'm guessing because ACF fields don't get appended to the post object.

//Does not work    
$image = $post -> services_block_image

ACF has the get_field() function, but what can I do to get the field for each of the posts from my original query? Found ACF docs to be rather confusing on this (goes without saying I'm a bit new to PHP).

1 Answer 1

2

Within loop use get_field function to get the image.

check below code for your reference.

 $image = get_field('services_block_image'); // get the image
 if( !empty($image) ): ?>

    <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

<?php endif; ?>
Sign up to request clarification or add additional context in comments.

1 Comment

This is not correct. This is only for while() loop, and not for foreach()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.