WPで画像を取り出す方法はたくさん用意されているが、
カスタムフィールドを利用してアップロードした場合、
get_post_custom()で画像IDを取り出し、
(注:カスタムフィールド自体にはソースでなくIDしか入っていない)
wp_get_attachment_image_src( $id ,$size)
でsrcを取り出し、imgタグに埋め込む方法が汎用性があり、好んで使っている。
この際、wp_get_attachment_image_src( $id ,$size)で取り出せるのはimgオブジェクトであり、ソースそのものではないので、このような形で取り込まれる。
array(4) {
[0]=>
string(75) “http://elementa.net/~.jpg”
[1]=>
int(120)
[2]=>
int(120)
[3]=>
bool(true)
}
ソースを取り出したいときは$img[0]などと取り出し、同様にしてサイズなども取り出せるので便利だ。
ちなみに$sizeを指定しない場合、サムネイルのサイズで出力される。
===========================================================================
追記
CODEX内のソース(特定のIDに紐づいた最初の画像を取り出す)
function echo_first_image ($postID) { $args = array( 'numberposts' => 1, 'order'=> 'ASC', 'post_mime_type' => 'image', 'post_parent' => $postID, 'post_status' => null, 'post_type' => 'attachment' ); $attachments = get_children( $args ); //print_r($attachments); if ($attachments) { foreach($attachments as $attachment) { $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' ); echo '<img src="'.wp_get_attachment_thumb_url( $attachment->ID ).'">'; } } }
コメント