如何从 wordpress 中的帖子页面 id 获取 acf 的画廊图片 url

Posted

技术标签:

【中文标题】如何从 wordpress 中的帖子页面 id 获取 acf 的画廊图片 url【英文标题】:How to get acf's gallery images url from post page id in wordpress 【发布时间】:2018-03-15 03:53:13 【问题描述】:

我已经使用 acf 插件为投资组合网站构建了自定义帖子模板 一个图片库有3~15张图片,每个帖子页面上的图片数量是相互的。 我想在页面模板上获取图片库 url 我已经获得了每个帖子页面的帖子 ID,并想从帖子 ID 中获取图片库 url

【问题讨论】:

你试过get_field('field_name', 22);吗? 22 是帖子的 ID。如果这不是您所需要的,那么您将需要展示您尝试过的代码示例。 是的,没错。我需要它但是在我的代码中, get_field('field_name', post_ID);不工作而不是这个,如果我回显get_sub_field('field_name',post_ID),它会显示最新的帖子ID的图片库 【参考方案1】:

我建议您查看 ACF 的文档,其中包含所有领域的出​​色代码示例。

https://www.advancedcustomfields.com/resources

要从帖子 ID 中获取图片 URL,您可以使用 get_field() 获取整个图片数组,然后遍历它们以获取 URL。

// get the array of all gallery images from the current post
$images = get_field( 'gallery' );

// get the array of all gallery images from the given post id
$post_id = 17;
$images = get_field( 'gallery', $post_id );

// example markup: create an unordered list of images
echo '<ul>';

// loop through the images to get the URL
foreach( $images as $image ) 

  // the url for the full image
  $image_url = $image['url'];

  // the url for a specific image size - in this case: thumbnail
  $image_thumbnail_url = $image['sizes']['thumbnail'];

  // render your markup inside this loop, example: an unordered list of images
  echo '<li>';
  echo '<img src="' . $image_url . '">';
  echo '</li>';



echo '</ul>';

每张图片本身就是一个数组,里面有你需要的一切:

Array (
  [ID] => 2822
  [alt] => 
  [title] => Hot-Air-Balloons-2560x1600
  [caption] => 
  [description] => 
  [mime_type] => image/jpeg
  [type] => image
  [url] => http://acf5/wp-content/uploads/2014/06/Hot-Air-Balloons-2560x1600.jpg
  [width] => 2560
  [height] => 1600
  [sizes] => Array (
    [thumbnail] => http://acf5/wp-content/uploads/2014/06/Hot-Air-Balloons-2560x1600-150x150.jpg
    [thumbnail-width] => 150
    [thumbnail-height] => 150
    [medium] => http://acf5/wp-content/uploads/2014/06/Hot-Air-Balloons-2560x1600-300x187.jpg
    [medium-width] => 300
    [medium-height] => 187
    [large] => http://acf5/wp-content/uploads/2014/06/Hot-Air-Balloons-2560x1600-1024x640.jpg
    [large-width] => 604
    [large-height] => 377
    [post-thumbnail] => http://acf5/wp-content/uploads/2014/06/Hot-Air-Balloons-2560x1600-604x270.jpg
    [post-thumbnail-width] => 604
    [post-thumbnail-height] => 270
  )
)

【讨论】:

感谢您对($b = 0 ; $b 那里的代码看起来不错。您的 get_field() 中的某些内容没有正确连接。您需要展示您尝试过的完整代码才能提供更多帮助。

以上是关于如何从 wordpress 中的帖子页面 id 获取 acf 的画廊图片 url的主要内容,如果未能解决你的问题,请参考以下文章

如何从一组自定义字段值中显示 Wordpress 帖子

如何从Wordpress管理员替换帖子和页面的所有外部/预览

WordPress中的自定义博客存档页面

如何从 Wordpress 页面/帖子中获取所有标签作为简码列表?

在functions.php中获取wordpress帖子ID

如何在 iframe 中的 wordpress 管理帖子页面中拥有可排序的 UI?