記事内の1番目の画像をサムネイルとして使用する

WordPressにはアイキャッチ機能がありますが、
アイキャッチ機能を使用せず、記事の一番上の画像をサムネイルとして使用する方法を紹介します。
テーマ内に functions.php を用意する
現在使っているテーマの「functions.php」を用意します。
無い場合は「functions.php」の名前でテーマフォルダ内に作成します。
functions.php にメソッドを追加する
記事から画像を抽出するメソッドを作成します。
<?php
// 画像取得(ID指定がなければ表示中の記事の画像を取得)
function catch_that_image($post_id = NULL)
{
if ( !empty($post_id) )
{
$posts = get_post($post_id);
$post_content = $posts->post_content;
}
else
{
global $post, $posts;
$post_content = $post->post_content;
}
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.*?src=(["\'])(.+?)\1.*?>/i', $post_content, $matches);
$first_img = $matches[2][0];
if ( empty($first_img) ) {
$first_img = '';
}
return $first_img;
}
?>
テーマに組み込む
<?php if (have_posts()) :
while (have_posts()) : the_post(); ?>
<div class="post">
<?php
// 記事内の一番最初の画像を取得
$img_url = catch_that_image();
if ( !empty($img_url) ): ?>
<a href="<?php the_permalink() ?>"><img src="<?php echo $img_url; ?>" alt="<?php the_title(); ?>" /></a>
<?php else: ?>
<a href="<?php the_permalink() ?>">No Image</a>
<?php endif; ?>
<div class="date"><?php the_time('Y.m.d') ?></div>
<div class="title"><?php the_title() ?></div>
</div>
<?php endwhile; ?>
<?php endif; ?>
記事一覧ページなどに組み込むことでサムネイルとして使用することができます。
投稿ごとにアイキャッチを設定するのが面倒な場合は、記事内から引っ張ってくるのも手ですね。
ただし画像サイズはそのままなので、あまり重い画像の場合は
ページ全体が重くなる原因にもなりますのでご注意ください。
関連記事






