wordpress 記事内の最初に登録された画像を所得 2016年1月2日
Tag:img | 画像
記事内の最初に登録された画像を所得して表示します。
1.まずfunctions.phpに下記を追加
//記事内の最初に使用されている画像を取得
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);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = esc_url(home_url('/wordpress/wp-content/themes/san/images/')) . 'blogimg.jpg';
}
return $first_img;
}
2.表示したい場所に下記を追加
<img src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" />