-
6月132011
WordPressで記事内の画像を取得
No CommentsWordPressは、記事本文以外に
「アイキャッチ画像」として画像を登録していれば
テンプレ内などで画像を取得する関数(WordPressのテンプレートタグ)を用意しています。Codex テンプレートタグ/the post thumbnail
が、アイキャッチ画像ではなく、
記事本文内にある画像を取得したい場合は、どうやら無さそうなので
「テンプレートタグ」を自作しました。メモしておきます。
下記のコードをテーマ内のfunction.phpに記述すれば、テーマ内で呼び出せます。
<?php get_the_content_image() ?>
いわゆるループ内で呼び出すタグです。
while ( have_posts() )
~
endwhile;
の間で呼び出すとそれぞれの記事から画像を取ってきます。
引数なし、返り値は画像URLです。// 記事内の画像を取ってくる function get_the_content_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ //Defines a default image $first_img = "/no-image.gif"; } return $first_img; }<?php get_the_contetn_image_by_postID($postid) ?>
ループ外で呼び出すタグです。
引数は記事ID(半角数字)、返り値は画像URLです。// 記事ID指定 function get_the_contetn_image_by_postID($postid) { $post=get_post($postid); $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ //Defines a default image $first_img = "/no-image.gif"; } return $first_img; }





