【WordPress】投稿の添付画像一覧をリンク付きで取得

Yuuです。

このブログはWordpressということで、折角なのでWordpressネタです。 投稿記事に添付された画像一覧を取得してみます。

投稿画像をリンク付きで出力

1
2
3
4
5
6
7
8
9
10
11
12
<?php
     $images = get_children(array(
          'post_parent' => $post->ID,
          'post_type' => 'attachment',
          'exclude' => get_post_thumbnail_id($post->ID),
          'post_mime_type' => 'image'
     ));
     foreach ( $images as $attachment_id => $attachment ) {
          $att_image_link = wp_get_attachment_link($attachment_id, 'thumbnail', true, false);
          echo $att_image_link;
     }
?>

get_childrenで投稿の添付ファイルを取得。

wp_get_attachment_linkで添付ファイルへのリンクを示すHTMLを取得。 設定としては、表示はthumbnailサイズ、リンクは出力という感じ。

投稿画像をリンク付きで出力

WPって、attachmentのimage.phpファイルとかの説明があまりないようなイメージなんですが、 image.phpとかで表示するならこんな感じでしょうか。

1
2
3
4
5
6
7
<?php
     if (wp_attachment_is_image($post->id)) {
        $att_image = wp_get_attachment_image_src( $post->id, "full-size");
        $att_image_name=$att_image[0];
        echo '<img src="' . $att_image_name .'" />';
     }
?>

wordpressはまだまだ勉強が足りないので、慣れていきたいところ。

Comments