今回は、投稿一覧を取得した際に表示させるサムネイル画像を投稿内の初めの画像にして、画像が無い場合は予め設定しといたデフォルト画像にする方法を紹介します。
WordPressの基本の仕様では無いのですが、クライアントからの要望は良くあります。基本仕様を覚えていれば少しの応用で可能なので、是非覚えてみて下さい。
記事内の最初の画像をサムネイルに設定
まずは、記事内の最初の画像をサムネイルにする設定を行います。
function.phpに以下の記述を追加して下さい。
// 投稿内初めの画像をサムネイルに
function icatch_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];
return $first_img;
}
global post関数を使用して投稿の初めの画像を取得して「icatch_that_image()」に格納します。
画像が無い場合はデフォルト画像を指定する方法
次に投稿内に画像がなかった場合に、表示するデフォルト画像の設定を行います。
先程のfunction.phpの「return $first_img」の前に以下の記述をします。(完成形は次で紹介します。)
if(empty($first_img)){
// 記事内で画像がなかったときのためのデフォルト画像を指定
$first_img = "https://www.example/wp/wp-content/themes/slag/img/image.JPG";
}
3行目の「first_img =」の後の「””」の中のパスで表示したい画像のパスを指定して下さい。
投稿内の初めをサムネにして無い場合はデフォルトに設定
完成形は以下です。これで準備は完了です。
// blog_thumb
function icatch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
// $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$output = preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){
// 記事内で画像がなかったときのためのデフォルト画像を指定
$first_img = "https://www.example/wp/wp-content/themes/slag/img/image.JPG";
}
return $first_img;
}
テンプレートファイルで呼び出して表示
function.phpで設定が完了したら、表示させたい箇所の、テンプレートphpに以下を記述して呼び出します。
<?php if (has_post_thumbnail()): ?>
<?php the_post_thumbnail(); ?>
<?php else: ?>
<img src="<?php echo icatch_that_image(); ?>" alt="<?php the_title(); ?>" />
<?php endif; ?>
4行目の「icatch_that_image()」で先ほど作成した設定内の画像を呼び出す事が出来ます。
以上が「記事内の最初の画像をサムネイルにして画像が無い場合はデフォルト画像を指定する方法」でした。
実務で使うリアルな要件ですので覚えていて損はないかと思います。