[WP]WordPress でメディアにアップされた画像を取得して表示する方法
スポンサード
スポンサード
WordPress のwp_get_attachment_url() 関数を使って、メディアに登録されている画像(添付ファイル)のURLを取得し、ブログに表示する方法のご紹介です。
メディアにアップロードされた画像のURLを取得して表示
まずはサンプルコードからご紹介します。1 2 3 4 5 6 7 | <?php $myposts = get_posts('post_type=attachment&post_mime_type=image&posts_per_page=1&orderby=rand'); if (have_posts()): foreach($myposts as $post) : ?> <img src="<?php echo wp_get_attachment_url($post->ID); ?>"> <?php endforeach; ?> <?php endif; ?> |
上記コードの2 行目で、post_type(投稿タイプ)はattachment とし、post_mime_type(添付ファイルのとき MIME タイプ)はimageにします。
5 行目は、wp_get_attachment_url() で取得した添付ファイルのURLを、img タグのsrc属性 に入れます。
上記の例だと、posts_per_page=1
、orderby=rand
にしており、1件の画像をランダムで表示できるようになりますので、例えば写真中心のブログであれば「今日の1枚」のような見せ方もできると思います。
また、以下のように画像の出力数や出力条件を変えてあげるだけで、
1 2 3 4 5 6 7 8 | <?php $myposts = get_posts('post_type=attachment&post_mime_type=image&posts_per_page=10&orderby=date'); if (have_posts()): foreach($myposts as $post) : ?> <h2><?php the_title(); ?></h2> <img src="<?php echo wp_get_attachment_url($post->ID); ?>"> <?php endforeach; ?> <?php endif; ?> |
例えばアップロード画像一覧のようなギャラリーページを用意することも可能です。
スポンサード
コメント