カテゴリー、タグ一覧表示のアイキャッチ画像周りの修正①でアイキャッチ画像の見た目を整えたので、次はPHPを編集して、アイキャッチ画像が設定されていない記事にもなにかしらの画像が表示されるように修正します。
アイキャッチ画像が設定されていなくても、記事内に画像が使用されている場合は、記事の最初に使用されている画像を自動的にアイキャッチとして表示するようにします。
また、記事内に画像を使用していない場合は、汎用のアイキャッチを表示させます。
PHPの編集
まずはfunctions.phpに以下の記述を付け足します。
if ( !function_exists('get_first_image_url_from_content') ) {
function get_first_image_url_from_content($post_content) {
if (empty($post_content)) return '';
if (preg_match('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $post_content, $matches)) {
return $matches[1];
}
return '';
}
}
記事の最初に使用されている画像を取得しています。
続いてworks-text.phpと、taxonomy-custom_tag.phpに共通する以下の部分を編集します。
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" class="hentry text" role="article">
<?php if ( has_post_thumbnail() ) : ?>
<figure class="eye-catch" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<?php
$thumbnail_id = get_post_thumbnail_id();
$eye_img = wp_get_attachment_image_src( $thumbnail_id , 'full' );
$url = $eye_img[0];
$width = $eye_img[1];
$height = $eye_img[2];
$size = $width.'x'.$height.' size-'.$width.'x'.$height;
$attr = array(
'class' => "attachment-$size eye-catch-image",
);
//アイキャッチの表示
if ($width && $height) {
the_post_thumbnail(array($width, $height), $attr);
} else {
the_post_thumbnail('full', $attr);
}
?>
</figure>
<?php endif; ?>
上のコードは修正前のものです。以下のように修正します。
<figure class="eye-catch" itemprop="image" itemscope itemtype="https://schema.org/ImageObject">
<a href="<?php the_permalink(); ?>" rel="bookmark">
<?php
if (has_post_thumbnail()) {
$thumbnail_id = get_post_thumbnail_id();
$eye_img = wp_get_attachment_image_src($thumbnail_id, 'full');
$url = $eye_img[0];
$width = $eye_img[1];
$height = $eye_img[2];
$size = $width . 'x' . $height . ' size-' . $width . 'x' . $height;
$attr = array(
'class' => "attachment-$size eye-catch-image",
);
if ($width && $height) {
the_post_thumbnail(array($width, $height), $attr);
} else {
the_post_thumbnail('full', $attr);
}
} else {
// アイキャッチがない場合は本文中の画像、それもなければ汎用アイキャッチ
$first_img_url = get_first_image_url_from_content(get_the_content());
$fallback_url = $first_img_url ? $first_img_url : get_template_directory_uri() . '/img/noimage.png';
echo '<img src="' . esc_url($fallback_url) . '" alt="" class="eye-catch-image" />';
}
?>
</a>
</figure>
記事本文中の中から最初に使われている画像を呼び出しています。EASELの親テーマのimgフォルダに汎用アイキャッチの「noimage.png」をアップロードし、設定されていない場合に呼び出せるようにしました。

今回用意したnoimage.png
また、以前のカスタマイズでアイキャッチ画像にリンクを設定しているので、この記事内で紹介していないカスタマイズが含まれています。
以上です!お疲れさまでした。