記事内で最初に使用されている画像の取得方法
記事の簡単な見出しを作ろうと思った時に記事で使用されている画像を使いたかったのでやり方メモ
- functions.phpに以下の関数を追加
function catch_that_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)){
$first_img = "/images/default.jpg"; // 記事に画像がなかった場合表示する
}
return $first_img;
}
- 表示したい箇所に記載する内容
<img src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" />
これで無事に最初の画像が取得できました!
以上