WordPressで画像名から画像を表示する必要がありました。
要件はこんな感じです。
- 画像はメニューの「メディア」からドンドンアップしたい
- 一方でデータはCSVでアップロードするので「画像名」欄に画像名を書いているのでその画像を拾って表示したい
要するに困っちゃうのはデータ自体をCSVでアップロードするので
ポストと画像を紐付けるのがネックでした。
で、思いついたのがこの方法です。
// 適宜イメージのタイトルを取得してください・・・例ではリクエストから取得するようにします。 $img01 = $_POST['img_name']; // get_page_by_title メソッドの第3引数(post_type)に'attachment'を指定しメディアを取得します。 // 第2引数はデフォルト OBJECT でオブジェクト型で返ってきます。 $img01_obj = get_page_by_title( $img01, NULL, 'attachment');
こうして取ったものを該当するものがあれば表示したい部分に下記コードを入れます。
<?PHP
if ($img02_obj != NULL ) {
// この例では幅を630ピクセル固定にしています。
?>
<img src="<?php echo $img02_obj->guid; ?>" width="630" />
<?php
}
?>
このコードの中の guid は画像のURLが入っている変数になります。
この他、下記の情報が取得できます。
object(WP_Post)#4326 (24) {
["ID"]=>
int(20323)
["post_author"]=>
string(1) "1"
["post_date"]=>
string(19) "2014-03-12 16:55:42"
["post_date_gmt"]=>
string(19) "2014-03-12 07:55:42"
["post_content"]=>
string(0) ""
["post_title"]=>
string(19) "サンプル画像2"
["post_excerpt"]=>
string(0) ""
["post_status"]=>
string(7) "inherit"
["comment_status"]=>
string(4) "open"
["ping_status"]=>
string(4) "open"
["post_password"]=>
string(0) ""
["post_name"]=>
string(11) "samplegraph"
["to_ping"]=>
string(0) ""
["pinged"]=>
string(0) ""
["post_modified"]=>
string(19) "2014-03-12 16:55:42"
["post_modified_gmt"]=>
string(19) "2014-03-12 07:55:42"
["post_content_filtered"]=>
string(0) ""
["post_parent"]=>
int(0)
["guid"]=>
string(64) "http://(URL)/wp-content/uploads/2014/03/sample.jpg"
["menu_order"]=>
int(0)
["post_type"]=>
string(10) "attachment"
["post_mime_type"]=>
string(10) "image/jpeg"
["comment_count"]=>
string(1) "0"
["filter"]=>
string(3) "raw"
本来この get_page_by_title はタイトルからページ情報を取得するためのメソッドですので画像を取得しているを紹介していますが、ページ情報取得してみてから利用してください。
「タイトル」っていうのは文字通り タイトル で the_title で表示されるもののことです。
上記のオブジェクト情報の [“post_title”] ですね。
なかなか便利な関数です。
