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

时间:2019-01-09 05:59:19

标签: php wordpress foreach advanced-custom-fields

对于具有特定页面模板的所有页面,我都有一个自定义图像字段(使用ACF插件)。

我正在查询这些页面,如下所示:

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

然后我正在显示带有foreach循环的页面:

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

现在,我想访问自定义字段以在循环内显示。但是,下面不起作用。我猜是因为ACF字段未附加到post对象。

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

ACF具有get_field()功能,但是我该怎么做才能从原始查询中获取每个帖子的字段?发现ACF文档对此颇为困惑(不用说我对PHP有点陌生)。

1 个答案:

答案 0 :(得分:1)

在循环内使用get_field函数获取图像。

检查下面的代码以供参考。

 $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; ?>
相关问题