アイキャッチ画像をサムネイルをして表示させる場合
<?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; }
トップページ
<div class="post-wrapper"> <?php $arg = array( 'posts_per_page' => 4, // 表示する件数 'orderby' => 'date', // 日付でソート 'order' => 'DESC', // DESCで最新から表示、ASCで最古から表示 'category_name' => 'web' // 表示したいカテゴリーのスラッグを指定 ); $posts = get_posts( $arg ); if( $posts ): ?> <?php foreach ( $posts as $post ) : setup_postdata( $post ); ?> <div class="post-box"> <a href="<?php the_permalink(); ?>"> <h3 class="post-title"><?php the_title(); ?></h3> <p class="post-img"><img src="<?php echo first_post_image(); ?>" ></p> <p class="cate-name"><?php $cat = get_the_category(); $cat = $cat[0]; { echo $cat->cat_name; } ?></p> </a> </div> <?php endforeach; ?> <?php endif; wp_reset_postdata(); ?> </div><!--/.post-wrapper-->
コメント