functions.php
<?php // 画像取得(ID指定がなければ表示中の記事の画像を取得)
function catch_that_image($post_id = NULL)
{
if ( !empty($post_id) ) {
$posts = get_post($post_id); $post_content = $posts->post_content;
} else {
global $post, $posts;
$post_content = $post->post_content;
}
$first_img = '';
ob_start(); ob_end_clean();
$output = preg_match_all('/<img.*?src=(["\'])(.+?)\1.*?>/i', $post_content, $matches);
$first_img = $matches[2][0];
if ( empty($first_img) ) {
$first_img = '';
}
return $first_img;
}
?>
archive.phpなどに
<?php if (have_posts()) :
while (have_posts()) : the_post(); ?>
<div class="post">
<?php
// 記事内の一番最初の画像を取得
$img_url = catch_that_image();
if ( !empty($img_url) ): ?>
<a href="<?php the_permalink() ?>"><img src="<?php echo $img_url; ?>" alt="<?php the_title(); ?>" /></a>
<?php else: ?> <a href="<?php the_permalink() ?>">No Image</a>
<?php endif; ?>
<div class="date"><?php the_time('Y.m.d') ?></div>
<div class="title"><?php the_title() ?></div>
</div>
<?php endwhile; ?>
<?php endif; ?>