wordpressで記事内の一番最初の画像を取得してサムネイル画像表示をする一般的なコードがあります。
functions.phpに以下のコードを書き、
<?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)){ //Defines a default image
$first_img = "画像がない場合の画像の場所";
}
return $first_img;
}
?>
表示したい場所に以下を入れ表示します。
<img src="<?php echo catch_that_image(); ?>" alt="" width="120" height="90" />
自分はよく新着情報などのループの中に入れて使ったりするのですが、このままだと”Windows Live Writer”などで記事を書いたりしたとき、最初の画像が取得できず最後の画像になってしまったりします。
そこで”preg_match_all”の部分を厳密にしてみます。
$output = preg_match_all("/<img[^>]+src=[\"'](s?https?:\/\/[\-_\.!~\*'()a-z0-9;\/\?:@&=\+\$,%#]+\.(jpg|jpeg|png|gif))[\"'][^>]+>/i", $post->post_content, $matches);
自分の場合、これで解消できています。
お悩みの方は試してみてはいかがでしょう。
1 Comment