投稿記事内の最初に使われている画像をサムネイル画像として表示させる
アイキャッチ画像をサムネイルをして表示させる場合
<?php the_post_thumbnail( array(240, 180) ); ?>
上記のテンプレートタグを使うと、imgタグごと出力されます。
投稿記事内の最初に使われている画像をサムネイル画像として表示させる場合
functions.php
function first_post_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 = get_template_directory_uri()."/common/img/base/ogimage.png"; } return $first_img; }
front-page.php
<?php $arg = array( 'posts_per_page' => 4, // 表示する件数 'orderby' => 'date', // 日付でソート 'order' => 'DESC', // DESCで最新から表示、ASCで最古から表示 'category_name' => 'site' // 表示したいカテゴリーのスラッグを指定 ); $posts = get_posts( $arg ); if( $posts ): ?> <?php foreach ( $posts as $post ) : setup_postdata( $post ); ?> <a href="<?php the_permalink(); ?>"> <li class="site_post_list"> <p class="site_post_thumbnail"><img src="<?php echo first_post_image(); ?>" ></p> <h3><?php the_title(); ?></h3> </li> </a> <?php endforeach; ?> <?php endif; wp_reset_postdata(); ?>