CHIPS

制作チップス

WordPressで投稿記事の最初の画像を表示する

2025年6月11日

カテゴリー: 制作チップス

トップページなどで新着情報の一覧を表示する際、画像もつけて出力したい場合のコード

サムネイル(アイキャッチ画像)付きで表示

<ul>
<?php
$posts = get_posts(array(
    'numberposts' => 10,
    'post_status' => 'publish',
));

if ($posts):
    foreach ($posts as $post):
        setup_postdata($post); ?>
        <li>
            <a href="<?php the_permalink(); ?>">
                <div class="thumb">
                    <?php
                    if (has_post_thumbnail()) {
                        the_post_thumbnail('thumbnail');
                    } else {
                        echo '<img src="' . esc_url(get_template_directory_uri()) . '/images/no-image.jpg" alt="no image">';
                    }
                    ?>
                </div>
                <div class="text">
                    <span><?php echo get_the_date(); ?></span>
                    <?php the_title(); ?>
                </div>
            </a>
        </li>
    <?php
    endforeach;
    wp_reset_postdata();
endif;
?>
</ul>

the_post_thumbnail() 引数の指定について

アイキャッチ画像のサイズや独自のclassなどを設定することができます。

the_post_thumbnail(サイズ, 属性)

サイズの指定は、以下のように設定します。

// サムネイルのサイズ
the_post_thumbnail('thumbnail');     
// 中サイズ
the_post_thumbnail('medium');           
// 大サイズ
the_post_thumbnail('large');
// 元のサイズ(アップロードした画像のサイズ)
the_post_thumbnail('full');
// サイズを数値で指定する場合
the_post_thumbnail(array(横幅, 縦幅));

サムネイルがない場合、投稿の最初の画像を代替する

functions.php

//投稿記事の最初の画像を表示
function catch_first_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  if($output) {
	$first_img = $matches [1] [0];
  } else {
	$first_img = get_template_directory_uri().'/images/enjel.jpg';
  }
  return $first_img;
}

代替画像 images/enjel.jpg は、テーマディレクトリ直下の /images/ フォルダ内に配置しておく

/wp-content/themes/my-theme/images/enjel.jpg

出力したい箇所に

<ul>
<?php
$posts = get_posts(array(
  'numberposts' => 10,
  'post_status' => 'publish',
));

if ($posts):
  foreach ($posts as $post):
    setup_postdata($post);
?>
    <li>
      <a href="<?php the_permalink(); ?>">
        <div class="thumb">
          <?php if (has_post_thumbnail()): ?>
            <?php the_post_thumbnail('thumbnail'); ?>
          <?php else: ?>
            <img src="<?php echo esc_url(catch_first_image()); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" />
          <?php endif; ?>
        </div>
        <div class="text">
          <span><?php echo get_the_date(); ?></span>
          <?php the_title(); ?>
        </div>
      </a>
    </li>
<?php
  endforeach;
  wp_reset_postdata();
endif;
?>
</ul>

functions.phpをいじりたくない場合や個々に画像を変えたい時などは、親テーマディレクトリまでのURLを取得する関数

<?php if (have_posts()): ?>
  <?php while (have_posts()): the_post(); ?>
    <div class="thumbnail">
      <?php if (has_post_thumbnail()): ?>
        <p><?php the_post_thumbnail('medium'); ?></p>
      <?php else: ?>
        <img 
          src="<?php echo esc_url(get_template_directory_uri()); ?>/img/damyimage.jpg" 
          width="400" 
          height="350" 
          alt="<?php echo esc_attr(get_the_title()); ?>">
      <?php endif; ?>
    </div>
  <?php endwhile; ?>
<?php endif; ?>

damyimage.jpg の置き場所

/wp-content/themes/my-theme/img/damyimage.jpg

サムネイルも本文画像もない場合だけダミー画像にする

投稿にサムネイルがなければ本文中の最初の画像を表示し、それもなければダミー画像を表示する

functions.php

function catch_first_image() {
    global $post;
    $first_img = '';

    // 投稿本文から <img> タグを正規表現で抽出
    if (preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)) {
        $first_img = $matches[1];
    }

    // 画像が見つからなければダミー画像にする
    if (empty($first_img)) {
        $first_img = get_template_directory_uri() . '/img/damyimage.jpg';
    }

    return $first_img;
}

投稿ループ内での画像表示コード(テンプレート内)

<?php if (have_posts()): ?>
  <?php while (have_posts()): the_post(); ?>
    <div class="thumbnail">
      <?php if (has_post_thumbnail()): ?>
        <?php the_post_thumbnail('medium'); ?>
      <?php else: ?>
        <img 
          src="<?php echo esc_url(catch_first_image()); ?>" 
          alt="<?php echo esc_attr(get_the_title()); ?>" 
          width="400" 
          height="350">
      <?php endif; ?>
    </div>
  <?php endwhile; ?>
<?php endif; ?>

image.jpgの置き場所

/wp-content/themes/my-theme/img/damyimage.jpg