すたらブログ

文系Webプログラマの備忘録

WordPress: 新着記事一覧で本文冒頭120文字と画像1枚を表示したい

目次


要望

  • 新着記事一覧に、題名と投稿日時だけでなく本文と画像を載せたい。
  • 本文は冒頭120文字だけを抜き出し、それ以降は「...」で省略したい。
  • 複数の画像がある場合は、最初の1枚だけを表示したい。


冒頭120文字だけを取得する

function.php

function my_get_lead ($content, $length = 120) {
  $stripped = strip_tags($content);
  $lead= mb_substr($stripped, 0, $length, 'utf-8');
  if (mb_strlen($stripped, 'utf-8') > $length) {
    $lead.= '...';
  }
  return $lead;
}

呼び出す

<?php echo my_get_lead(get_the_content()) ?>

最初の1枚の画像を取得する

function.php

function my_get_first_img ($content) {
  preg_match('/<img [^>]+>/i', $content, $matches);
  return $matches[0];
}

呼び出す

<?php echo my_get_first_img(get_the_content()) ?>

実際の使用例

上の写真では、Bootstrapの「リストグループ」と「メディアオブジェクト」を使って見やすく表示しています。

<h3>新着記事</h3>
<?php $postslist = get_posts(array('posts_per_page' => 10)); ?>
<?php if (count($postslist) > 0) : ?>
  <ol class="list-group news-list">
    <?php foreach ($postslist as $post) : setup_postdata( $post ); ?>
      <li class="list-group-item">
        <div class="media">
          <div class="media-body">
            <h4 class="media-heading">
              <a href="<?php the_permalink(); ?>">
              <?php the_title(); ?>
              <small><?php the_time(get_option('date_format')); ?></small>
              </a>
            </h4>
            <div><?php echo my_get_lead(get_the_content()) ?></div>
          </div>
          <div class="media-right">
            <?php echo my_get_first_img(get_the_content()) ?>
          </div>
        </div>
      </li>
    <?php endforeach; wp_reset_postdata(); ?>
  </ol>
<?php endif; ?>