
WordPress の検索結果(search.php)やタグ(tag.php)、カテゴリページ(category.php)に表示されるタイトルリストに、記事中に使用される最初の画像を表示する方法。
/wp-includes.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 = "/no-image.gif";
}
return $first_img;
}
スポンサードリンク
使用例
/ に no-image.gif を適当につくって置く。
if (have_posts()) : while (have_posts()) : the_post(); ?> <div> <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2> <p><a href="<?php the_permalink() ?>"><img style="border:1px solid #333333;padding:3px;" src="<?php echo catch_that_image(); ?>" /></a></p> <a href="<?php the_permalink() ?>">この記事を読む</a> </div>
※WordPress 3.1.2 で動作確認した
参考文献
- やりたかったあの機能を実現する、WordPress 中級者必見のカスタマイズ6個 | gerenuk.crazyphoto.org/


コメント