サイドバーなどのサムネイル画像として、記事内の最初の画像を取り出す場合。
サムネイル画像が登録されていない場合は、記事内の画像をサムネイルとして利用する。
// 投稿データを取得
$args = array(
'post_type' => '投稿タイプ名',
'posts_per_page' => 5,
'post_status' => publish,
);
$post_array = get_posts($args);
if ($post_array) {
// 投稿データ分繰り返す
foreach ($post_array as $post_data) {
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_item->post_content, $matches);
$first_img = $matches[1][0];
}
}
$outputには、画像があるかないかの判断を0と1で判断。ひとつでもあると1が入る。
$matches[1]にはsrc属性のimgパスが多次元配列で入っている。
// 以下をfunction.phpに追記
// returnは画像パスが入る
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(has_post_thumbnail()) {
$image_id = get_post_thumbnail_id ();
$image_url = wp_get_attachment_image_src ($image_id, true);
$first_img = $image_url[0];
} elseif(empty($first_img)){
$first_img = get_bloginfo("template_url")."/img/no_image.png";
}
return $first_img;
}
// 以下のようにbackground画像として利用する場合 <div class="thumb"<?php if(catch_that_image()): ?> style="background: url(<?php echo catch_that_image() ?>) no-repeat scroll center center / cover transparent;"<?php endif; ?>></div>