WordPressの記事に挿入された画像をサムネイルとしてサイズ指定し取得する
クライアントにサムネイルを設定して、投稿してくださいねはちょっとハードルが高すぎる
ということで、記事に挿入された画像を取得しthumbnailとして使用したい。
だが、しかしページや配置場所によって、ひとつのサイズじゃ困るというときに模索したちょっと強引かもな方法以下
function.phpに記載
<?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)){
$first_img = esc_url(get_template_directory_uri()) . '/images/common/dummy.jpg';
}else{
//記事本文に挿入され自動生成された150×150サイズを取得
$first_img = substr_replace($first_img, '-150x150',strrpos($first_img,'.'),0) ;
}
return $first_img;
}
function catch_that_image02() {
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)){
$first_img = esc_url(get_template_directory_uri()) . '/images/common/dummy.jpg';
}else{
//記事本文に挿入され自動生成された300×200サイズを取得
$first_img = substr_replace($first_img, '-300x200',strrpos($first_img,'.'),0) ;
}
return $first_img;
}
?>
多分もっとスマートに書く方法あると思うんだけどもとりあえずいつもやり方を忘れてしまうのでメモ
catch_that_image01
catch_that_image02
と増やしてるだけ
使用するページや投稿のphpに挿入し取得して表示するソース例
//150×150の場合 <img src="<?php echo catch_that_image(); ?>" alt="<?php the_title(); ?>" /> //300×200の場合 <img src="<?php echo catch_that_image02(); ?>" alt="<?php the_title(); ?>" />
