将特色图像作为对象检索

时间:2014-11-06 作者:Staffan Estberg

我想将帖子的特征图像作为对象检索(array) 以获得所有图像大小。

这个get_the_post_thumbnail() 函数不能这样做,有什么想法吗?

3 个回复
最合适的回答,由SO网友:passatgt 整理而成

首先获取注册的图像大小和特色图像附件id:

$sizes = get_intermediate_image_sizes();
$post_thumbnail_id = get_post_thumbnail_id();
遍历已注册的大小并创建一个数组:

$images = array();
foreach ( $sizes as $size ) {
    $images[] = wp_get_attachment_image_src( $post_thumbnail_id, $size );
}
组合为一个函数,用于放置内部函数。php:

function get_all_image_sizes($attachment_id = 0) {
    $sizes = get_intermediate_image_sizes();
    if(!$attachment_id) $attachment_id = get_post_thumbnail_id();

    $images = array();
    foreach ( $sizes as $size ) {
        $images[] = wp_get_attachment_image_src( $attachment_id, $size );
    }

    return $images;
}
用法:

$featured_image_sizes = get_all_image_sizes();

SO网友:Sean Michaud

这是老生常谈,但上述答案并不完全。要正确获取所有图像属性的所有图像大小,还需要获取附件对象。

类似这样:

if ( has_post_thumbnail() ) {
    $thumb = array();
    $thumb_id = get_post_thumbnail_id();

    // first grab all of the info on the image... title/description/alt/etc.
    $args = array(
        \'post_type\' => \'attachment\',
        \'include\' => $thumb_id
    );
    $thumbs = get_posts( $args );
    if ( $thumbs ) {
        // now create the new array
        $thumb[\'title\'] = $thumbs[0]->post_title;
        $thumb[\'description\'] = $thumbs[0]->post_content;
        $thumb[\'caption\'] = $thumbs[0]->post_excerpt;
        $thumb[\'alt\'] = get_post_meta( $thumb_id, \'_wp_attachment_image_alt\', true );
        $thumb[\'sizes\'] = array(
            \'full\' => wp_get_attachment_image_src( $thumb_id, \'full\', false )
        );
        // add the additional image sizes
        foreach ( get_intermediate_image_sizes() as $size ) {
            $thumb[\'sizes\'][$size] = wp_get_attachment_image_src( $thumb_id, $size, false );
        }
    } // end if

    // display the \'custom-size\' image
    echo \'<img src="\' . $thumb[\'sizes\'][\'custom-size\'][0] . \'" alt="\' . $thumb[\'alt\'] . \'" title="\' . $thumb[\'title\'] . \'" width="\' . $thumb[\'sizes\'][\'custom-size\'][1] . \'" height="\' . $thumb[\'sizes\'][\'custom-size\'][2] . \'" />\';
} // end if

SO网友:Sjoerd Oudman

好的,几年后再更新一次。我想你现在已经管理好了;)。但对于那些希望执行此操作并返回与(比方说)ACF图像对象一致的内容并允许您轻松填充源集的人来说。您可以在函数中执行类似的操作。php:

function get_all_image_sizes($attachment_id = 0) {
  $sizes = get_intermediate_image_sizes();
  if(!$attachment_id) $attachment_id = get_post_thumbnail_id();

  $images = array();
  foreach ( $sizes as $size ) {
    $images[$size] = wp_get_attachment_image_src( $attachment_id, $size )[0];
  }
  $imageObject = array(
    \'sizes\' => $images
  );

  return $imageObject;
} 
然后你可以这样使用它

   $thumbID = get_post_thumbnail_id();
   $image = get_all_image_sizes($thumbID);
   $html = \'<img src="\'. $image[\'sizes\'][\'large\'] .\'" alt="">\';

结束

相关推荐