【问题标题】:Get ACF field data within foreach loop - wordpress在 foreach 循环中获取 ACF 字段数据 - wordpress
【发布时间】:2019-06-03 20:50:22
【问题描述】:

我为具有特定页面模板(使用 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 有点陌生)。

【问题讨论】:

    标签: php wordpress foreach advanced-custom-fields


    【解决方案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; ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2020-01-03
      • 2019-05-23
      • 2021-03-23
      相关资源
      最近更新 更多