wordpress5.7.3で投稿記事の最初の画像のサムネイルを取得して表示させる動作が不安定になり、表示出来たりできなかったりしたため、過去のコードを見直した。
preg_match_allの記述を変更
変更前
preg_match_all('/<img.+?class=".+?wp-image-(.+).*?".*?>/i', $post->post_content, $matches);
変更後
preg_match_all( '/<img.+class=[\'"].*wp-image-([0-9]+).*[\'"].*>/i', $post->post_content, $matches );
function.phpにこちらを記述する(全体)
記事内に画像が無い場合の代替画像「default1.png」
/* ---------------------------------------------------------------------------------------
◆◆◆ 投稿記事の最初の画像のサムネイル ?php echo my_first_image_thumb(); ? で表示 ####
------------------------------------------------------------------------------------------*/
function my_first_image_thumb(){
global $post, $posts;
$img_url = '';
//デフォルト画像の設定
$defaute_url = get_stylesheet_directory_uri(). '/images/default1.png';
//最初の画像を取得してIDを取得
preg_match_all( '/<img.+class=[\'"].*wp-image-([0-9]+).*[\'"].*>/i', $post->post_content, $matches );
if(isset($matches[1][0])){
$img_id = ($matches[1][0]);
}
//最初の画像があれば分岐
if(!empty($img_id)){
//最初の画像IDからサムネイルのパスを取得してセット
$img_url = my_wp_get_attachment_medium_url($img_id);
} else {
//最初の画像がない場合、デフォルト画像のパスをセット
$img_url = $defaute_url;
}
return $img_url;
}
//画像IDからサムネイルサイズのパスを取得(画像サイズ変更可能)
//画像サイズ (thumbnail, medium, large, full or custom size)
function my_wp_get_attachment_medium_url( $id ) {
$thumbnail_array = image_downsize( $id, 'thumbnail' );
$thumbnail_path = $thumbnail_array[0];
return $thumbnail_path;
}
ページ内の表示させたい部分に以下を記述
<img src="<?php echo my_first_image_thumb(); ?/>">