ブログ記事の一番最初の画像のサムネイルを表示する方法
wordpressで、クライアントに更新してもらう場合、
アイキャッチの部分に写真を入れてもらえれば一番いいのですが、
PCに疎い人の場合、ブログの中には画像を入れることはするかもしれないけど、
アイキャッチの部分に画像を入れてくださいといっても入れてくれない場合が多いです。
そして、そんな中、
トップページなどや記事一覧で、記事のサムネイル画像を表示するためにコードを書いていても
アイキャッチに入れていないと画像のサムネイルが表示されずレイアウトもキレイに収まりません。
なので、ブログ記事本文中の一番最初の画像をサムネイル画像にして、
表示するのがいいという言になります。
方法はこちら
↓
Function.phpに記載します
// 新着情報一覧に画像取得
function catch_that_image_thumbnail() {
global $post;
if ( preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) ) {
$first_img = $matches[1][0];
$first_img_thumbnail = substr_replace($first_img, '-500x380',strrpos($first_img,'.'),0) ;
} else {
$first_img_thumbnail = get_stylesheet_directory_uri(). '/images/default-500x380.png';
}
return $first_img_thumbnail;
}
そうそうこちらも忘れずに!!
↓
//サムネイル画像追加
function add_thumbnail_size() {
add_theme_support( 'post-thumbnails' );
add_image_size( 'tnbbig-thumbnails', 500, 380, true );
}
add_action( 'after_setup_theme', 'add_thumbnail_size' );
実際に表示させたい部分はこちらで記載します
↓
<img src="<?php echo catch_that_image_thumbnail(); ?>" />
————————————————————
こんな風に、2種類の違うサイズも作れます!
// 新着情報一覧に画像取得 500px × 380px 用
function catch_that_image_thumbnail() {
global $post;
if ( preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) ) {
$first_img = $matches[1][0];
$first_img_thumbnail = substr_replace($first_img, '-500x380',strrpos($first_img,'.'),0) ;
} else {
$first_img_thumbnail = get_stylesheet_directory_uri(). '/images/default-500x380.png';
}
return $first_img_thumbnail;
}
// 新着情報一覧に画像取得 80 × 80 用
function catch_that_image_thumbnail2() {
global $post;
if ( preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) ) {
$first_img = $matches[1][0];
$first_img_thumbnail = substr_replace($first_img, '-80x80',strrpos($first_img,'.'),0) ;
} else {
$first_img_thumbnail = get_stylesheet_directory_uri(). '/images/default-80x80.png';
}
return $first_img_thumbnail;
}
表示箇所には、以下のように、
<img src="<?php echo catch_that_image_thumbnail(); ?>" />
や
<img src="<?php echo catch_that_image_thumbnail2(); ?>" />
でOKです!!
関連記事はこちら!
スポンサーリンク






