アイキャッチ画像がない場合に投稿の最初の画像を使う。
2019年5月17日
ちょっとハマったのでコードだけメモ。
いろいろ調べてみても
$first_img = $matches [1] [0];
としか出てこなかったがここがoffsetエラー。
そこで
if(isset($matches[1][0])){
$first_img = ($matches[1][0]);
}
に変更することでエラー回避!!
/*
top-page news画像を投稿最初の画像から取得
*/
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"][^>]*>/i', $post->post_content, $matches);
if(isset($matches[1][0])){
$first_img = ($matches[1][0]);
}
if(empty($first_img)){// 記事内で画像がなかったときのためのデフォルト画像を指定
$first_img = bloginfo('template_directory')."/images/common/topnews-default.png";
}
return $first_img;
}