代码之家  ›  专栏  ›  技术社区  ›  geochanto

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

  •  1
  • geochanto  · 技术社区  · 6 年前

    我为所有具有特定页面模板的页面(使用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 回复  |  直到 6 年前
        1
  •  1
  •   geochanto    6 年前

    环内使用 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; ?>