先日、サイト更新依頼をいただいた際に、
アイキャッチ画像を設定していない投稿ページで
カテゴリ一覧に、画像を表示させてほしい。との希望をいただきました。
アイキャッチ画像を設定していない投稿ページの一覧を作成するのは初めてだったので、
あれこれググって、記事内の1枚目の画像を取得して設置してみました。
備忘録のために残しておきます。
スポンサードリンク
投稿ページの最初の画像の取得方法
まずは、【functions.php】への記載。
function catch_first_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 = "/images/default.jpg"; } return $first_img; }
表示させたい部分への出力コード
<img src="<?php echo catch_first_image(); ?>" alt="<?php the_title(); ?>" />
カテゴリ一覧や、関連記事などのサムネイルの代わりに使用しました。
スポンサードリンク