简体   繁体   English

在 foreach 循环中获取 ACF 字段数据 - wordpress

[英]Get ACF field data within foreach loop - wordpress

I have a custom image field for all pages with a specific page template (using ACF plugin).我为具有特定页面模板的所有页面(使用 ACF 插件)提供了一个自定义图像字段。

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:然后我用 foreach 循环显示页面:

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.我猜是因为 ACF 字段不会附加到 post 对象。

//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? ACF 有get_field()函数,但是我该怎么做才能从原始查询中获取每个帖子的字段? Found ACF docs to be rather confusing on this (goes without saying I'm a bit new to PHP).发现 ACF 文档在这方面相当混乱(不用说我对 PHP 有点陌生)。

Within loop use get_field function to get the image.在循环内使用get_field函数来获取图像。

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; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM