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).
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; ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.