如何从wordpress中的帖子页面ID获取acf的图库图片网址

时间:2017-10-03 20:53:39

标签: javascript php wordpress blogs

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

获取图片库网址

1 个答案:

答案 0 :(得分:1)

我建议您查看ACF的文档,其中包含适用于所有字段的优秀代码示例。

util.inspect

要从帖子ID获取图片网址,您可以使用https://www.advancedcustomfields.com/resources获取整个图片数组,然后循环浏览它们以获取网址。

// 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
  )
)